SICP)연습문제 1.6

2009년 6월 28일 at 3:49 am

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)
5
(new-if (= 1 1) 0 5)
0
Delighted, Alyssa uses new-if to rewrite the square-root program:
file:///G:/ebooks/MIT%20Press%20-%20Structure%20an…puter%20Programs,%202nd%20Edition/book-Z-H-10.html (19 of 27) [8/17/2008 4:40:23 PM]
Structure and Interpretation of Computer Programs
(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.

A)

위와 같이 식을 썼을 때 sqrt 을 실행하면 sqrt-iter 가 실행될 때 먼저 new-if 의 값을 구하려고 한다.

new-if의 값은 cond 를 사용하도록 정의되어 있기 때문에 인자들을 cond 에 다시 넣고 sqrt-iter 를 수행한다. sqrt-iter 에는 new-if 가 있기 때문에 인자들을 다시 cond 에 넣고 sqrt-iter 를 수행한다.. 무한반복이다. new-if 가 아닌 if 라면 기본형이기 때문에 다시 평가하지 않아 수행에 문제가 없다.