my attempt to do the exercises in sicp.

Thursday, July 17, 2008

sicp exercise 2.33



;   Exercise 2.33. Fill in the missing expressions to complete the following definitions of some
;   basic list manipulation operations as accumulations:
;   (define (map p sequence)
;   (accumulate (lambda (x y) <??>) nil sequence))
;   (define (append seq1 seq2)
;   (accumulate cons <??> <??>))
;   (define (length sequence)
;   (accumulate <??> 0 sequence))

(define (accumulate op init seq)
        (cond ((null? seq) init)
      (else (op (car seq) (accumulate op init (cdr seq))))))

(define (map1 p sequence)
    (accumulate (lambda (x y) (cons (p x) y)) (list) sequence))

(display (map1 (lambda (y) (+ y 10)) (list 1 2 3 4 5))) (newline)

(define (append1 seq1 seq2)
    (accumulate cons seq2 seq1))

(display (append1 (list 1 2 3 4) (list 9 8 7 6 ))) (newline)

(define (length1 seq)
    (accumulate (lambda (x y) (+ 1 y)) 0 seq))

(display (length1 (list 1 2 3 4 5 1 2 2 3 4 5 6 7))) (newline)

No comments: