📁
SICP
  • README
  • Building Abstractions With Procedures
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
Powered by GitBook
On this page
  • Exercise 1.6: Alyssa P. Hacker doesn’t see why if needs to be provided as a special form. “Why can’t I just define it as an ordinary procedure in terms of cond?” she asks. Alyssa’s friend Eva Lu Ator claims this can indeed be done, and she defines a new version of if:
  • Eva demonstrates the program for Alyssa:
  • Delighted, Alyssa uses new-if to rewrite the square-root program:
  • What happens when Alyssa attempts to use this to compute square roots? Explain.

Was this helpful?

  1. Building Abstractions With Procedures

6

Exercise 1.6: Alyssa P. Hacker doesn’t see why if needs to be provided as a special form. “Why can’t I just define it as an ordinary procedure in terms of cond?” she asks. Alyssa’s friend Eva Lu Ator claims this can indeed be done, and she defines a new version of if:

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

Eva demonstrates the program for Alyssa:

(new-if (= 2 3) 0 5)
(new-if (= 1 1) 0 5)

Delighted, Alyssa uses new-if to rewrite the square-root program:

(define (sqrt-iter guess x) (new-if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))

What happens when Alyssa attempts to use this to compute square roots? Explain.

(define (improve guess x)
       (average guess (/ x guess)))

(define (average x y)
  (/ (+ x y) 2))

(define (good-enough? guess x)
(< (abs (- (square guess) x)) 0.001))
(define (new-sqrt x)
    (sqrt-iter 1.0 x)
)
(new-sqrt 9)

Timeout!

But the special form if will make sure the recursive happens only the predicate is not met.

Previous5Next7

Last updated 4 years ago

Was this helpful?

, so it evaluates all the parameters for the new-if; that makes sqrt-iter execute in whether cases, which cause infinite loop in consequences.

Because Scheme Lisp is in applicative order