Log in Page Discussion History Go to the site toolbox

Exercise 3.54

From BluWiki

Section 3.5 Exercises

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 <??> <??>)))


  • We want the nth element (starting from 0) of factorials to be <math>(n+1)!</math>.
  • So, for <math>n>1</math>, the (n-1)th element of (mul-streams <??> <??>) should <math>(n+1)!</math>.
  • Therefore, the (n-1)th element of (mul-streams <??> <??>) should be equal to <math>n+1</math> times the (n-1)th element of factorials (starting from 0).
  • To generate a stream for which the (n-1)th element (starting from 0) is <math>n+1</math>, we can use (integers-starting-from 2).

The reasoning, in pseudo-Scheme:

  (stream-ref factorials n)
= (* (stream-ref factorials (- n 1))
                 (+ n 1))
= (* (stream-ref factorials                 (- n 1))
     (stream-ref (integers-starting-from 2) (- n 1)))
= (stream-ref
             (mul-streams
                         factorials
                         (integers-starting-from 2)))
             (- n 1))

The complete definition of factorials is:

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

Site Toolbox:

Personal tools
GNU Free Documentation License 1.2
This page was last modified on 19 October 2007, at 18:19.
Disclaimers - About BluWiki