Reputation: 673
I saw that a similar question was asked before, but I don't understand another issue here.
Here are two functions:
(define x 2)
(define a 2)
(define goo
(lambda (x)
(display x)
(lambda (y) (/ x y))))
(define foo
(let ((f (goo a)))
(lambda (x)
(if (= x 0)
x
(f x)))))
What is the return value of (foo (foo 0))
? What will print out to the screen?
As I understand it, when I run (foo 0)
in the beginning, 2
will print out (we will enter the function goo
), and the return value will be 0
. Then, we will enter the function foo
again with (foo (foo 0))
=> (foo 0)
. We again enter the function goo
and 2
will print out. But when I run it, 2
is printed just once. I think I'm missing a critical issue about let
and its connection to lambda
.
Upvotes: 1
Views: 2992
Reputation: 41220
The let
inside the definition of foo
, and therefore the application of goo
to a
, is evaluated when foo
is defined, not when foo
is evaluated.
Look at it this way: what is the value of foo? It is the lambda
expression. The binding of f
is closed over by foo
, it is not "redone" every time foo
is evaluated.
Edit: here's an example without lambda
s
> (let ((x (sqrt 2))) (* x 3))
4.24264068711929
> (define bar (let ((x (sqrt 2))) (* x 3)))
> bar
4.24264068711929
>
When you evaluate bar
you are not calling sqrt
again. bar
is defined as the body of the let
, in this case a number that is the result if an expression.
In your example the body of the let
is a lambda
expression. But just like my example, the let
binding is not re-executed.
Upvotes: 2