help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Closures - do you understand them well?


From: Michael Heerdegen
Subject: Re: Closures - do you understand them well?
Date: Thu, 08 Dec 2022 20:53:31 +0100
User-agent: Gnus/5.13 (Gnus v5.13)

Tassilo Horn <tsdh@gnu.org> writes:

> Shocking!!!

The example is written in a way to suggest a wrong result.  But don't we
all rely on the behavior demonstrated from time to time?  The
implementation of `letrec' for example:

(macroexpand-1 '(letrec ((f (lambda () f)))))
==> (let (f) (setq f (lambda nil f)))

We expect that the value of F in the closure bound to F references the
closure itself, not the initial value.

>  Common Lisp agrees:
>
> (let ((funs '()))
>   (loop for i from 1 to 3
>      do (push (lambda () i) funs))
>   (apply #'+ (mapcar #'funcall funs)))
> ;=> 12

I guess this depends a bit on the implementation of `loop'.  But I think
the result is expected, yes.  Don't you remember what you learned about
shared environments that different places in the code have access to
(including the ability to modify)?

> So I guess the reason is that the `i' is not an integer but a place
> where the integers 1, 2, and 3?

It's a free variable in all the lambdas, and it refers to the binding in
the same environment.  When the `apply' call is made the binding in that
environment is the one from the moment when it was last changed in the
loop, and that is `4`.  That's all.

Michael.




reply via email to

[Prev in Thread] Current Thread [Next in Thread]