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: Fri, 09 Dec 2022 22:21:28 +0100
User-agent: Gnus/5.13 (Gnus v5.13)

Tassilo Horn <tsdh@gnu.org> writes:

> This time I'm prepared and have three versions making a new binding.
> Take this, Michael! :-)

Wow - ok, let's see...

> (let ((i 0)
>       (m (lambda (i)
>            (lambda () i)))
>       funs)
>   (while (< i 100)
>     (push (funcall m i) funs)
>     (cl-incf i))
>   (mapcar #'funcall funs))

Yes, I think one can do this (the argument variable i shadows the
variable of the same in the `let', but it also exists to conserve the
value from the outside i so one can argue that it's ok to use the same
name - it's semantically not incorrect anyway).  Nice solution.

> (let ((i 0)
>       funs)
>   (while (< i 100)
>     (let ((j i))
>       (push (lambda () j) funs))
>     (cl-incf i))
>   (mapcar #'funcall funs))

This is the trick that is used in the implementation of `dolist': create
a binding that lives only inside the evaluation of the body of the loop
in one iteration step.

> (let ((i 0)
>       funs)
>   (while (< i 100)
>     (push `(lambda () ,i) funs)
>     (cl-incf i))
>   (mapcar #'funcall funs))

Hmm...hmm.  No, we don't want to quote lambdas.  When Stefan sees that
he might install a patch that will make the above error (he really could
do this!).  Better only do that privately.

> Oh, I forgot to `nreverse` funs so my Nth function returns 99-N instead.
> Good enough...

Ok, it still counts (but maybe backwards).


Regards,

Michael.




reply via email to

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