2.33 Exercise 2.33
To implement map using accumulate, we give accumulate a
procedure consing the result of applying p to its first argument
(the new value) onto its second argument (the accumulated list so far).
And since accumulate evolves a recursive process, the values of the
new sequence will be in the right order.
(define (accumulate op initial sequence) | (if (null? sequence) | initial | (op (car sequence) | (accumulate op initial (cdr sequence))))) |
|
(define (map p sequence) | (accumulate (lambda (x y) (cons (p x) y)) nil sequence)) |
|
To implement append, we set up one sequence as the initial value and
apply cons to successive elements from the other. The second argument
is used as the initial value because cons will append new values to
the front of the list.
(define (append seq1 seq2) | (accumulate cons seq2 seq1)) |
|
To implement length, we give a procedure that adds 1 to its second argument.
(define (length sequence) | (accumulate (lambda (x y) (+ y 1)) 0 sequence)) |
|