0

Exercise 1.6 defines a new-if with cond:

(define (new-if predicate then-clause else-clause)
  (cond (predicate then-clause)
        (else else-clause)))

This new-if would fall into infinite loop when called in a recursion.

Example sqrt-iter illustrates the fact that arguments are evaluated immediately after passing into a user-defined function.

The (infinite)stream introduced in 3.5 is also defined a function:

(define (cons-stream a b)
  (cons a
        (delay b)))

The key point to build it, according to the text book, is delay.

But supposed you build a stream:

(define (intgers-starting-from n)
  (cons-stream n
               (intgers-starting-from (+ n 1))))

(define integers (intgers-starting-from 1))

Using the same evaluator as it in new-if, you won't get it working because (intgers-starting-from n) would always evaluate (intgers-starting-from (+ n 1)) and obviously there is no end to it despite how delay is implemented.

Is it contradictory that SICP assumes such evaluator that works for cons-stream but not for new-if?

Rahn
  • 4,787
  • 4
  • 31
  • 57

1 Answers1

4

SICP says:

Cons-stream is a special form defined so that

(cons-stream <a> <b>)

is equivalent to

(cons <a> (delay <b>))

It also adds:

Although stream-car and stream-cdr can be defined as procedures, cons-stream must be a special form. If cons-stream were a procedure, then, according to our model of evaluation, evaluating (cons-stream <a> <b>) would automatically cause <b> to be evaluated, which is precisely what we do not want to happen. For the same reason, delay must be a special form, though force can be an ordinary procedure.

By definition, a special form is not a procedure or function. So, your definition of cons-stream is incorrect.

It's usually implemented as a macro:

(define-syntax cons-stream
  (syntax-rules ()
    ((cons-stream a b)
     (cons a (delay b)))))

Indeed, you can define new-if as a macro and it'd work correctly too:

(define-syntax new-if
  (syntax-rules ()
    ((new-if predicate then-clause else-clause)
     (cond (predicate then-clause)
           (else else-clause)))))
C. K. Young
  • 219,335
  • 46
  • 382
  • 435