title: Scheme / Racket Best Practice - Recursion vs Variable Accumulation
body: <p>I'm new to Scheme (via Racket) and (to a lesser extent) functional programming, and could use some advise on the pros and cons of accumulation via variables vs recursion.  For the purposes of this example, I'm trying to calculate a moving average.  So, for a list <code>'(1 2 3 4 5)</code>, the 3 period moving average would be <code>'(1 2 2 3 4)</code>.  The idea is that any numbers before the period are not yet part of the calculation, and once we reach the period length in the set, we start averaging the subset of the list according the chosen period.</p>
  
  <p>So, my first attempt looked something like this:</p>
  
  <pre><code>(define (avg lst)
    (cond
     [(null? lst) '()]
     [(/ (apply + lst) (length lst))]))
  
  (define (make-averager period)
    (let ([prev '()])
      (lambda (i)
        (set! prev (cons i prev))
        (cond
         [(&lt; (length prev) period) i]
         [else (avg (take prev period))]))))
  
  (map (make-averager 3) '(1 2 3 4 5))
  
  &gt; '(1 2 2 3 4)
  </code></pre>
  
  <p>This works.  And I like the use of map.  It seems composible and open to refactoring.  I could see in the future having cousins like:</p>
  
  <pre><code>(map (make-bollinger 5) '(1 2 3 4 5))
  (map (make-std-deviation 2) '(1 2 3 4 5))
  </code></pre>
  
  <p>etc.</p>
  
  <p>But, it's not in the spirit of Scheme (right?) because I'm accumulating with side effects.  So I rewrote it to look like this:</p>
  
  <pre><code>(define (moving-average l period)
    (let loop ([l l] [acc '()])
      (if (null? l)
          l
          (let* ([acc (cons (car l) acc)]
                 [next
                   (cond
                    [(&lt; (length acc) period) (car acc)]
                    [else (avg (take acc period))])])
            (cons next (loop (cdr l) acc))))))
  
   (moving-average '(1 2 3 4 5) 3)
   &gt; '(1 2 2 3 4)
  </code></pre>
  
  <p>Now, this version is more difficult to grok at first glance.  So I have a couple questions:</p>
  
  <ol>
  <li><p>Is there a more elegant way to express the recursive version using some of the built in iteration constructs of racket (like <code>for/fold</code>)?  Is it even tail recursive as written?</p></li>
  <li><p>Is there any way to write the first version without the use of an accumulator variable?</p></li>
  <li><p>Is this type of problem part of a larger pattern for which there are accepted best practices, especially in Scheme?</p></li>
  </ol>