An early Lisp program (circa Feb. 1960)
funcall.blogspot.com
funcall.blogspot.com
Modern version:
(defun collapse (l)
(cond ((atom l) (cons l nil))
((null (cdr l))
(cond ((atom (car l)) l)
(t (collapse (car l)))))
(t (append (collapse (car l))
(collapse (cdr l))))))
(collapse '(((A B) ((C))) ((D (E F)) (G) ((H)))))
;=> (A B C D E F G H)
[1]: http://www.reddit.com/r/lisp/comments/fpfnf/an_early_lisp_pr...I'm grateful for this accident. The absence of commas is one of the key features that led me to see s-expressions as mapping very nicely into web templates.
(defun flatten (x)
(labels ((rec (x acc)
(cond ((null x) acc)
((atom x) (cons x acc))
(t (rec (car x) (rec (cdr x) acc))))))
(rec x nil))) (defn flat [s]
(if (sequential? s)
(apply concat (map flat s))
(list s)))
(flat '((((1 2 3)) (4 5)) (((((((6 7 [8 9])))))) a b c) {:a 1 :b 2}))
;=> (1 2 3 4 5 6 7 8 9 a b c {:a 1, :b 2}) (defun flatten (list)
(mapcan (lambda (item)
(if (listp item) (flatten item) (list item)))
list))It made it sound like the program outputs those 2 lines, which would win any C obfuscation contest.
For example, in Clojure I'd write the flatten function as:
(defn flatten [x]
(remove sequential? (tree-seq sequential? seq x)))
Other lisps probably have similar functions. int fib(int n) {
if(n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
(defun fib (n)
(if (< n 2)
n
(+ (fib (- n 1)) (fib (- n 2)))))
The parens aren't really that annoying once you get used to them, and I personally find them a lot less distracting than the profusion of commas and curly braces that C-syntax languages use in their place. Eg: {{"apples", RED}, {"bananas", YELLOW}, {"oranges", ORANGE}}
'(("apples" RED) ("bananas" YELLOW) ("oranges" ORANGE))
Also, don't forget that abstraction makes everything more readable: (dolist (var '(1 2 3 4)) (princ a))
for(list::iterator itr = list.begin(); itr != list.end(); ++itr) {
cout << *itr;
}Trying to judge what Lisp is from that code is akin to trying to judge what airplanes are from something the Wright brothers built in their bicycle shop.
I used a symbolics machine to code list back in the 80s.