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: Tassilo Horn
Subject: Re: Closures - do you understand them well?
Date: Fri, 09 Dec 2022 21:55:49 +0100
User-agent: mu4e 1.9.4; emacs 30.0.50

Michael Heerdegen <michael_heerdegen@web.de> writes:

> everyone): how to "fix" the code so that what some people expected is
> the end result?...:
>
>  Write an expression that returns a list of 100 functions accepting zero
>  arguments.  `funcall'ing the Nth function must return N.  Use a `while'
>  loop or whatever you like but please not `dolist' or any tool that
>  already handles this "problem" specifically.

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

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

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

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

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

Bye,
Tassilo



reply via email to

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