An Early LISP Program
March 1, 2011
Here’s our exact translation of that program to Scheme:
(define (collapse l)
(cond ((atom? l) (cons l '()))
((null? (cdr l))
(cond ((atom? (car l)) l)
(else (collapse (car l)))))
(else (append (collapse (car l))
(collapse (cdr l))))))
These examples come from the original Fox program listing:
> (collapse '((((a b) ((c))) ((d (e f)) (g) ((h))))))
(a b c d e f g h)
> (collapse '((a (b (c (d (e))) f (g (h j))))))
(a b c d e f g h j)
> (collapse '((((((a) b) c) d) e)))
(a b c d e)
You might find it instructive to compare collapse
, given above, to the flatten
function of the Standard Prelude, which performs the same task. If your Scheme system doesn’t provide atom?
, use this:
(define (atom? x)
(and (not (pair? x)) (not (null? x))))
You can run the program at http://programmingpraxis.codepad.org/U3q3yRDV .
[…] today’s Programming Praxis exercise, our goal is to write a function to un-nest a list. Let’s get […]
My Haskell solutions (see http://bonsaicode.wordpress.com/2011/03/01/programming-praxis-an-early-lisp-program/ for a version with comments):
Solution 1:
Solution 2:
Solution 3:
Basically a translation:
I was curious whether I could get a more “Pythonic” version going, since this could run up against
Python’s recursion limit if fed a suitably hideous list. Without much time today, I decided to research
what others had come up with; I ran across this “trampolined-style” version, which is certainly stretching my mind a bit.
Here’s a generator that returns the items of the input iterable in “flattened-order”.
You have to collect the output in a list or tuple. Note that handling of strings is
somewhat ambiguous in python, because a string is an iterable. I chose to treat strings
as atoms rather than nested iterables.
Likely to raise an exception if the input is nested more than 1000 deep.
Nice generator, Mike! If you wanted to avoid the import, you could use
and then modify your line 10 as needed (or just call
hasattr(arg, "__iter__")
directly in line 10).[…] Aujourd’hui, j’écrirais ce programme comme ça : ; Flatten a Slist (i.e [Sexp]) ; Slist -> [Symbol] (define collapse (lambda (lst) (mappend collapse-sexp lst))) ; Flatten a Sexp (Symbol | Slist) ; Sexp -> [Symbol] (define collapse-sexp (lambda (sexp) (if (list? sexp) (collapse sexp) (list sexp)))) […]
Thanks Graham.
Here are two non-recursive versions. The first flattens a list ‘in-place’, the second is a generator that works with nested Iterables.
run the code here