title: Racket/Scheme Flatten Explanations
body: <p>Can someone help me to break down exactly the order of execution for the following versions of flatten?  I'm using Racket.</p>
  
  <p>version 1, is from racket itself, while version two is a more common? implementation.</p>
  
  <pre><code>(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)))]))
  </code></pre>
  
  <p>Now, running the first example with '(1 2 3) produces:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>while the second produces: </p>
  
  <pre><code>l = (1 2 3)
  l = 1
  l = (2 3)
  l = 2
  l = (3)
  l = 3
  l = ()
  '(1 2 3)
  </code></pre>
  
  <p>The order of execution seems different.  In the first example, it looks like the second loop <code>(loop (cdr l) acc)</code> 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.</p>
  
  <p>I'm going through the Little Schemer but these are more difficult examples that I could really use some help on.</p>
  
  <p>Thanks a lot.</p>