I'm trying to learn lambda calculus and Scheme Lisp. The tutorial on lambda calculus can be found here http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf.
The problem I'm facing is I don't know how to properly implement iteration.
(define (Y y) (((lambda (x) (y (x x))) (lambda (x) (y (x x))))))
(define (sum r n) ((is_zero n) n0 (n succ (r (pred n)))))
(display ((Y sum) n5))
I always get this error:
Aborting!: maximum recursion depth exceeded
I know the problem is about the evaluation order: the scheme interprets (Y sum)
first, which results in infinite recursion:
((Y sum) n5) -> (sum (Y sum) n5) -> ((sum (sum (Y sum))) n5) -> .... (infinite recursion)
but I want
((Y sum) n5) -> ((sum (Y sum) n5) -> (n5 succ ((Y sum) n4)) -> .... (finite recursion)
How can I solve this problem? thanks.
if
statement. In clojureif
is not a function, it's a special keyword that doesn't evaluate the second branch when condition is true. Howeverif
is a function in lambda-calculus where branches are arguments. Clojure evaluates arguments eagerly, one of them being a recursive call hence the StackOverflowError – Westcott