t3x.org / nss / fold-right.html

(Nils' Scheme Snippets)

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

(fold-right proc2 form . forms) => form

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

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