2008. 5. 29.

연습문제 2.39

(define (reverse1 sequence)
  (fold-right (lambda (x y) (append y (list x))) nil sequence))
(define (reverse2 sequence)
  (fold-left (lambda (x y) (cons y x)) nil sequence))

연습문제 2.38

fold-right와 fold-left는 리스트에서 연산하는 순서가 정반대이다.
따라서 fold-right에서 (op x y)처럼 수행하는 연산자를
fold-left에서는 (op y x)처럼 수행하도록 변경해서 입력해주면 두 함수는 동일한 연산을 한다.

연습문제 2.37

(define (dot-product v w)
  (accumulate + 0 (map * v w)))

(define (matrix-*-vector m v)
  (map (lambda (x) (dot-product v x)) m))


(define (transpose mat)
  (accumulate-n cons nil mat))

(define (matrix-*-matrix m n)
  (let ((cols (transpose n)))
    (map (lambda (row) (matrix-*-vector cols row)) m)))

연습문제 2.36

(define (accumulate-n op init seqs)
  (if (null? (car seqs))
      nil
      (cons (accumulate op init (map car seqs))
            (accumulate-n op init (map cdr seqs)))))

연습문제 2.35

(define (count-leaves-acc t)
(accumulate + 0 (map (lambda (x) (+ 0 1))
(enumerate-tree t))))

연습문제 2.34

(define (horner-eval x coefficient-sequence)
  (accumulate (lambda (this-coeff higher-terms) (+ (* highter-terms) this-coeff))
              0
              coefficient-sequence))

연습문제 2.33

(define (map_test p sequence)
  (accumulate (lambda (x y) (cons (p x) y)) nil sequence))

(define (append_test seq1 seq2)
  (accumulate cons seq2 seq1))

(define (length_test sequence)
  (accumulate
   (lambda (x y)
     (+ 1 y))
   0 sequence))