Skip to content

Instantly share code, notes, and snippets.

@mohanrajendran
Last active August 29, 2015 14:03
Show Gist options
  • Save mohanrajendran/1d671d56baaff2d4f598 to your computer and use it in GitHub Desktop.
Save mohanrajendran/1d671d56baaff2d4f598 to your computer and use it in GitHub Desktop.
SICP Exercise 1.6
(define (new-if predicate then-clause else-clause)
  (cond (predicate then-clause)
        (else else-clause)))

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

Rewriting the if function on our own reverts the evaluation to applicative-order. This means all the arguments are expanded and evaluated in the first run. Thus running the code produces the following:-

(sqrt-iter 1.0 2)

(new-if (good-enough? 1.0 2)
        1.0
        (sqrt-iter (improve 1.0 2)
                   2))

(new-if (< (abs (- (square 1.0) 2)) 0.001)
	1.0
	(sqrt-iter (average 1.0 (/ 2 1.0))
		   2))

(new-if (< (abs (- 1.0 2)) 0.001)
 	1.0
	(sqrt-iter 1.5 2))

(new-if (< 1.0 0.001)
	1.0
	(new-if (good-enough? 1.5 2)
        	1.5
		(sqrt-iter (improve 1.5 2)
                   	   2)))

...

(new-if (< 1.0 0.001)
	1.0
	(new-if (< 0.25 0.001)
        	1.5
		(sqrt-iter 1.4167 2)))

...

Note:- cond is not expanded for clarity

Thus, in this case. The predicate, then-clause and else-clause are all evaluated first. Thus, irrespective of the condition, both clauses are evaluated. Because the else-clause contains another new-if statement, this means that the evaluation continues recursively down ad infinitum even if a terminal case is reached. Thus the evauation does not terminate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment