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: Thu, 08 Dec 2022 20:06:59 +0100
User-agent: mu4e 1.9.3; emacs 30.0.50

Michael Heerdegen <michael_heerdegen@web.de> writes:

> What is the return value of the following expression, and what's your
> reasoning?  Answer without asking Emacs:

Obviously 6.

> #+begin_src emacs-lisp
> ;; -*- lexical-binding: t -*-
>
> (let ((i 0)
>       (funs '()))
>   (while (< (setq i (1+ i))
>             4)
>     (push (lambda () i)
>           funs))
>   (apply #'+ (mapcar #'funcall funs)))
> #+end_src

Shocking!!!  Common Lisp agrees:

--8<---------------cut here---------------start------------->8---
(let ((funs '()))
  (loop for i from 1 to 3
     do (push (lambda () i) funs))
  (apply #'+ (mapcar #'funcall funs)))
;=> 12
--8<---------------cut here---------------end--------------->8---

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

Well, at least rust gets this right:

--8<---------------cut here---------------start------------->8---
fn main() {
    let mut funs = vec![];
    let mut i: i32 = 1;
    while i < 4 {
        funs.push(move || i);
        i += 1;
    }
    let result: i32 = funs.iter().map(|f| f()).sum();
    println!("Result = {}", result); // 6, that's right!
}
--8<---------------cut here---------------end--------------->8---

Bye,
Tassilo



reply via email to

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