SICP Exercise 3.68 Louis Reasoner pairs

Exercise 3.68.  Louis Reasoner thinks that building a stream of pairs from three parts is unnecessarily complicated. Instead of separating the pair (S0,T0) from the rest of the pairs in the first row, he proposes to work with the whole first row, as follows:

(define (pairs s t)
  (interleave
   (stream-map (lambda (x) (list (stream-car s) x))
               t)
   (pairs (stream-cdr s) (stream-cdr t))))


Does this work? Consider what happens if we evaluate (pairs integers integers) using Louis's definition of pairs.

SOLUTION

Louis Reasoner's procedure will not work. It will run into an infinite loop. Not having an outer 'stream-cons', there is no delayed operation to prevent the program from getting into an infinite loop.

When 'louis-reasoner-pairs' executes, 'interleave' needs to be run. But before that, it's arguments need to be evaluated. The second argument is a call to louis-reasoner-pairs again. This puts the program into an infinite loop.

The code and tests are here.

Comments

Popular posts from this blog

SICP Exercise 2.56 differentiation rule

SICP Exercise 1.28 (Miller-Rabin Test)

SICP Exercise 4.18 a alternative strategy for interpreting internal definitions