fold
another common idiom
- compute a value from a list by
starting with some base value b
repeatedly applying some procedure to the value so far and the next element of the list
- write a procedure that expresses this pattern
(define (fold proc b p) (if (null? p) b (proc (fold proc b (cdr p)) (car p))))
- which way does fold go? does it associate elements to the left or right?
sample uses of fold
- (define (sum p) (fold + 0 p))
- (define (product p) (fold * 1 p))
- (define (posmax p) (fold max 0 p))
- (define (contains p x) (fold (lambda (s e) (or s (= e x))) #f p)