乐正

Actions speak louder than words.

Sicp-ex3-54

问题

请定义一个与add-streams相似的过程mul-streams,对于下面两个输入流,它按元素逐个生成乘积。用它和integers流一起完成下面流的定义,其中第$n$个元素(从$0$开始数)是$n+1$的阶乘:

1
(define factorials (cons-stream 1 (mul-streams <??> <??>)))

解答

先定义mul-streams如下:

1
2
(define (mul-streams s1 s2)
  (stream-map * s1 s2))

factorials可以如下定义:

1
2
(define factorials
  (cons-stream 1 (mul-streams factorials (stream-cdr integers))))

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
(stream-ref factorials 0)
;Value: 1

(stream-ref factorials 1)
;Value: 2

(stream-ref factorials 2)
;Value: 6

(stream-ref factorials 3)
;Value: 24

(stream-ref factorials 4)
;Value: 120

draft

« sicp-ex3-53 sicp-ex3-55 »

Comments