title: Functional Programming - Implementing Scan (Prefix Sum) using Fold
body: <p>I've been teaching myself functional programming, and I'm currently writing different higher order functions using folds. I'm stuck implementing scan (also known as prefix sum). My map implementation using fold looks like:</p>
  
  <pre><code>(define (map op sequence)
    (fold-right (lambda (x l) (cons (op x) l)) nil sequence))
  </code></pre>
  
  <p>And my shot at scan looks like:</p>
  
  <pre><code>(define (scan sequence)
    (fold-left (lambda (x y) (append x (list (+ y (car (reverse x)))))) (list 0) sequence))
  </code></pre>
  
  <p>My observation being that the "x" is the resulting array so far, and "y" is the next element in the incoming list. This produces:</p>
  
  <pre><code>(scan (list 1 4 8 3 7 9)) -&gt; (0 1 5 13 16 23 32)
  </code></pre>
  
  <p>But this looks pretty ugly, with the reversing of the resulting list going on inside the lambda. I'd much prefer to not do global operations on the resulting list, since my next attempt is to try and parallelize much of this (that's a different story, I'm looking at several CUDA papers).</p>
  
  <p>Does anyone have a more elegant solution for scan?</p>
  
  <p>BTW my implementation of fold-left and fold-right is:</p>
  
  <pre><code>(define (fold-left op initial sequence)
   (define (iter result rest)
    (if (null? rest)
     result
     (iter (op result (car rest)) (cdr rest))))
   (iter initial sequence))
  
  (define (fold-right op initial sequence)
   (if (null? sequence)
    initial
    (op (car sequence) (fold-right op initial (cdr sequence)))))
  </code></pre>