[plt-scheme] what is fold-left?

From: Joe Marshall (jmarshall at alum.mit.edu)
Date: Thu Feb 12 19:05:52 EST 2009

(define (fold-left procedure init list)

  (define (fold-left-error irritant)
    (error:not-list irritant 'FOLD-LEFT))

  (define (fold-left-loop state element tail)
    (if (pair? tail)
        (fold-left-loop (procedure state element) (car tail) (cdr tail))
        (begin (if (not (null? tail))
                   (fold-left-error tail))
               (procedure state element))))

  (if (pair? list)
      (fold-left-loop init (car list) (cdr list))
      (begin (if (not (null? list))
                 (fold-left-error tail))

On Wed, Feb 11, 2009 at 7:11 PM, Mike Eggleston <mikeegg1 at me.com> wrote:
> Morning,
> I'm looking at some code at
> <http://funcall.blogspot.com/2007/08/naive-bayesian-classifier.html>. This
> code by default will not run in DrScheme. The code is using (fold-left
> ...). Looking at the function it looks like a (map ...), but I don't
> (yet) know why I can't just use a 'map' instead of the 'fold-left'.
> Any ideas? What does this function do that 'map' doesn't and why
> should it be used?

Because `map' doesn't do what you want.
MAP takes a function and a list and returns a new list.

FOLD-LEFT takes a function, a (initial) value, and a list
and then walks down the list applying the function to
the current value and the head of the list to generate
the next value.  Here is an example:

(define (sum f list)
  (fold-left (lambda (sum element)
               (+ sum (f element)))

on each iteration, we apply f to the head of the list
and add it to the accumulated sum.  For example:

(sum string-length '("Foo" "bar" "hello"))  => 11

(map string-length '("Foo" "bar" "hello")) => (3 3 5)

Feel free to ask other questions.


Posted on the users mailing list.