1; SketchyLISP Library 2; Copyright (C) 2006,2007 Nils M Holm. All rights reserved. 3; See the file LICENSE of the SketchyLISP distribution 4; for conditions of use. 5 6; ---name--- 7; fold-left 8 9; ---conformance--- 10; R5.91RS 11 12; ---purpose--- 13; Iterate over lists. Combine the base element 14; .V b 15; with the list of the first members of each given list. 16; Combine the result with the list of their second 17; members, etc. 18; When the given lists are empty, return the base 19; element. 20; .B 21; All lists passed to 22; .C fold-left 23; must have the same length. 24 25; ---args--- 26; F - function to apply 27; B - base element 28; A* ... - lists 29 30; ---keywords--- 31; FOLD-LEFT function, folding, lists, left-associative 32 33; ---see-also--- 34; fold-right, map, member, list? 35 36; ---example--- 37; :l lib/list.scm 38; (fold-left list '1 '(a b c) '(d e f)) => (((1 a d) b e) c f) 39 40(define fold-left #t) 41 42; (require "nullp.scm") ; null? 43(require "map-car.scm") 44 45; ---code--- 46(define (fold-left f b . a*) 47 (letrec 48 ((carof 49 (lambda (a) 50 (map-car car a))) 51 (cdrof 52 (lambda (a) 53 (map-car cdr a))) 54 (fold 55 (lambda (a* r) 56 (cond ((null? (car a*)) r) 57 (else (fold (cdrof a*) 58 (apply f r (carof a*)))))))) 59 (cond ((null? a*) 60 (bottom '(too few arguments to fold-left))) 61 ((null? (car a*)) b) 62 (else (fold a* b))))) 63