t3x.org / nss / fold-left.html

(Nils' Scheme Snippets)

 
Paren matching: ON  |  Category: lists  |  Overview  |  Scheme Books  |  License
 

(fold-left proc2 form . lists) => form

 
Purpose
Fold lists to values, left-associative version. Combine the base element with the list of the first members of each given list. Combine the result with the list of their second members, etc:
(fold-left f 0 '(a b c)) = (f (f (f 0 a) b) c)
When the given lists are empty, return the base element.
 
Arguments
f combining function
b base element
a* lists
 
Example
(fold-left cons 0 '(a b c)) => (((0 . a) . b) . c)
(define (fold-left f b . a*)
  (letrec
    ((carof
       (lambda (a)
         (map car a)))
     (cdrof
       (lambda (a)
         (map cdr a)))
     (fold
       (lambda (a* r)
         (cond ((null? (car a*)) r)
           (else (fold (cdrof a*)
                       (apply f r (carof a*))))))))
    (if (null? a*)
        (wrong "fold-left: too few arguments")
        (fold a* b))))

Copyright (C) 2007 Nils M Holm <nmh @ t3x . org>