SICP 問題 2.33(アキュムレータを使って map、append、length を定義してみる)

【問題】

リスト操作の基本演算の、アキュムレーションとしての定義が以下にある。掛けた部分を補って完成せよ。

(define (map p sequence)
  (accumulate (lambda (x y) <??>) nil sequence))

(define (append seq1 seq2)
  (accumulate cons <??> <??>))

(define (length sequence)
  (accumulate <??> 0 sequence))

【解答】

accumulate の定義はこれ。

(define (accumulate op initial sequence)
  (if (null? sequence)
      initial
      (op (car sequence)
	  (accumulate op initial (cdr sequence)))))

で、こいつを使って map、append、length を定義してみるとのこと。
まずは map。

(define (map p sequence)
  (accumulate (lambda (x y) (cons (p x) y)) '() sequence))

では実験。


gosh> (map (lambda (x) (* x x)) (list 1 2 3 4 5 6 7))
(1 4 9 16 25 36 49)
gosh>
OKOK。じゃ次、append。

(define (append seq1 seq2)
  (accumulate cons seq2 seq1))

では実験。


gosh> (append (list 1 2 3 4) (list 5 6 7))
(1 2 3 4 5 6 7)
gosh>
これもOK。じゃ最後、length。

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

では実験。


gosh> (length (list 1 2 3 4 5 6 7 "ほげほげ"))
8
gosh>
おっけ〜。