Friday, 5 October 2012

Difference between if and customized if as new-if

Suppose we wanted to define a function new-if which acts just like if; for instance,
(if (< 2 3) 4 5) => 4
and likewise
(new-if (< 2 3) 4 5) => 4
This is not too hard to write:
 
(define new-if
  (lambda (test then-exp else-exp)
    (cond [test then-exp]
          [else else-exp])))

This even seems to work. But there is something deeply wrong with this definition. Try stepping through (fact 4) for the following definition of fact:
 
(define fact
  (lambda (x)
    (new-if (< x 3)
           x
           (* n (fact (- n 1))))))

No application of fact ever halts--the function keeps calling itself recursively forever.

The problem is that functions (such as new-if) always evaluate all their arguments, while special forms (such as if and cond) may only evaluate some of their arguments, leaving others as expressions rather than values. We can't use the ordinary part of Scheme to write new special forms, only new functions.


Theory behind the new-if is the explanation regarding tail recursion which was explained in previous blog post.

                                           ......Thank You......

No comments:

Post a Comment