SICP exercise 1.5 and 1.6
Asked Answered
A

2

6

In addition to question What's the explanation for Exercise 1.6 in SICP?. So Dr. Racket (R5RS) evaluates sqrt-iter function with "if" in finite time, clearly showing normal order evaluation. But if I use example from exercise 1.5

(define (p) (p))
(define (test x y)
  (if (= x 0)
      0
      y))
(test 0 (p))

it goes into infinite loop, making me think "if" uses applicative order evaluation. So where am I wrong?

Aggrieved answered 11/9, 2012 at 21:8 Comment(0)
B
10

What happens is that the if is never reached: precisely because of the applicative order of evaluation both arguments to test get evaluated before actually calling test, and the expression (p) will loop forever.

If the same procedure were evaluated using normal order it would return zero, that's what this example is trying to demonstrate in the first place.

Bost answered 11/9, 2012 at 21:43 Comment(0)
S
3

Using DrRacket with a #lang scheme directive in the first line, I tried it this way ...

;say "hi" to Ben Bitdiddle

(define (q) (display "Hello?...Ben?)

(define (test x y)
(if (= x 0) 
    0
    y))

Then I used the DrRacket 5.3 debug tool to step through the evaluation.
It's clearly applicative-order evaluation.

Eval window shows -> Hello? ... Ben? followed by a 0 cuz DrRacket evaluates the call to (q) before entering the "if".

Skylark answered 20/10, 2012 at 22:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.