Can someone help me to break down exactly the order of execution for the following versions of flatten? I’m using Racket.
version 1, is from racket itself, while version two is a more common? implementation.
(define (flatten1 list)
(let loop ([l list] [acc null])
(printf "l = ~a acc = ~a\n" l acc)
(cond [(null? l) acc]
[(pair? l) (loop (car l) (loop (cdr l) acc))]
[else (cons l acc)])))
(define (flatten2 l)
(printf "l = ~a\n" l)
(cond [(null? l) null]
[(atom? l) (list l)]
[else (append (flatten2 (car l)) (flatten2 (cdr l)))]))
Now, running the first example with ‘(1 2 3) produces:
l = (1 2 3) acc = ()
l = (2 3) acc = ()
l = (3) acc = ()
l = () acc = ()
l = 3 acc = ()
l = 2 acc = (3)
l = 1 acc = (2 3)
'(1 2 3)
while the second produces:
l = (1 2 3)
l = 1
l = (2 3)
l = 2
l = (3)
l = 3
l = ()
'(1 2 3)
The order of execution seems different. In the first example, it looks like the second loop (loop (cdr l) acc) is firing before the first loop since ‘(2 3) is printing right away. Whereas in the second example, 1 prints before the ‘(2 3), which seems like the first call to flatten inside of append is evaluated first.
I’m going through the Little Schemer but these are more difficult examples that I could really use some help on.
Thanks a lot.
The main difference is this:
flatten1works by storing the output elements (first from thecdrside, then from thecarside) into an accumulator. This works because lists are built from right to left, so working on thecdrside first is correct.flatten2works by recursively flattening thecarandcdrsides, thenappending them together.flatten1is faster, especially if the tree is heavy on thecarside: the use of an accumulator means that there is no extra list copying, no matter what. Whereas, theappendcall inflatten2causes the left-hand side of theappendto be copied, which means lots of extra list copying if the tree is heavy on thecarside.So in summary, I would consider
flatten2a beginner’s implementation of flatten, andflatten1a more polished, professional version. See also my implementation of flatten, which works using the same principles asflatten1, but using a left-fold instead of the right-fold thatflatten1uses.(A left-fold solution uses less stack space but potentially more heap space. A right-fold solution uses more stack and usually less heap, though a quick read of
flatten1suggests in this case that the heap usage is about the same as my implementation.)