Exercise 3.54. Define a procedure mul-streams, analogous to add-streams, that produces the elementwise product of its two input streams. Use this together with the stream of integers to complete the following definition of the stream whose nth element (counting from 0) is n + 1 factorial:
(define factorials (cons-stream 1 (mul-streams <??> <??>)))
首先我们需要定义 mul-streams,其定义与 add-stream 一样。具体 add-stream 与 map-stream 的工作原理分析见 3.5.2 无限流 。
(define (mul-streams s1 s2)
(stream-map * s1 s2))
在补全 factorials 的时候,我们只要注意到,第 n 个位置的 factorials 值只需要乘以第 n+1 个位置的 integers 就可以得到 (n+1)! 的结果,就可以写出 factorials 的流的形式。
(define factorials
(cons-stream 1 (mul-streams (stream-cdr integers) factorials)))
;;; tests begin
(load "../testframe.scm")
(assert= (stream-ref factorials 0) 1) ;1!
(assert= (stream-ref factorials 1) 2) ;2!
(assert= (stream-ref factorials 2) 6) ;3!
(assert= (stream-ref factorials 3) 24) ;4!
(assert= (stream-ref factorials 4) 120) ;5!