乐正

Actions speak louder than words.

Sicp-ex2-33

问题

请填充下面缺失的表达式,完成将一些基本操作看做累积的定义:

1
2
3
4
5
6
7
8
(define (map p sequence)
  (accumulate (lambda (x y) <??>) nil sequence))

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

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

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
(define (map p sequence)
  (accumulate (lambda (x y)
                (cons (p x) y))
              (list)
              sequence))

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

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

测试

1
2
3
4
5
6
7
8
(map square (list 1 2))
;Value 14: (1 4)

(append (list 1 2) (list 3))
;Value 16: (1 2 3)

(length (list 1 2 3 4))
;Value: 4

draft

« sicp-ex2-32 sicp-ex2-34 »

Comments