Reputation: 1941
I am trying to implement a while loop using recursion with lambda, but I just don't understand how to do it.
I am supposed to start with this lambda expression:
((lambda (x) (x x)) (lambda (x) (x x))
My first question is why does this cause 'eternal' recursion? I try to understand how it works, but I just can't grasp it.
I also have this code to go after:
((lambda (x) (x x))
(lambda (x)
(if (not (= i 0))
(begin
(display i)
(set! i (- i 1))
(x x))
)))
This code causes a loop that prints from i = n to i = 0, but I don't understand this either. If someone would care to explain the use of lambda here I would be grateful :)
Edit: I have to use this lambda expression as my 'starting point', and I don't want to use macros (it's a voluntary excercise which I try to understand, so I want to follow the guidelines :))
Upvotes: 2
Views: 2640
Reputation: 31147
To see what happens when ((lambda (x) (x x)) (lambda (x) (x x))
is evaluated use the stepper in DrRacket. It can show you the steps an evaluation takes.
Write your expression in the definition window of DrRacket. Then choose the teaching language "Intermediate Student with lambda". Then click the stepper button (the green triangle followed by a bar).
You will see something that looks like the image (which uses a different program):
Update:
Try this program:
(define i 5)
((lambda (x) (x x))
(lambda (x)
(if (not (= i 0))
(x x)
'ignore)))
Update:
(define i 5)
(define f
(lambda (x)
(if (not (= i 0))
(begin
(display i)
(set! i (- i 1))
(x x))
'done)))
(f f)
Or without any defines at all:
((lambda (f) (f f))
(lambda (x)
(if (not (= i 0))
(begin
(display i)
(set! i (- i 1))
(x x))
'done)))
And here without an external variable:
((lambda (f i) (f f i))
(lambda (x i)
(if (not (= i 0))
(begin
(display i)
(x x (- i 1)))
'done))
5)
Using a while
function:
(define (while body . args)
(apply body body args))
(while (lambda (loop i)
(if (not (= i 0))
(begin
(display i)
(loop loop (- i 1)))
'done))
5)
Upvotes: 2