Skip to content

Closures do not close in comprehensions #2243

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
lsb opened this issue Apr 9, 2012 · 4 comments
Closed

Closures do not close in comprehensions #2243

lsb opened this issue Apr 9, 2012 · 4 comments
Labels

Comments

@lsb
Copy link

lsb commented Apr 9, 2012

In the REPL on coffeescript.org:

comprehended = ((() -> alert i) for i in [0..10])
mapped = [0..10].map( (i) -> ( () -> (alert(i)) ));

comprehended[5]()  // 11
mapped[5]()  // 5

This is unintuitive.

@paulmillr
Copy link

You need to use do notation to preserve context. In this case:

comprehended = ((do (i) -> -> alert i) for i in [0..10])

@michaelficarra
Copy link
Collaborator

Yeah, this is consistent with JS behaviour. CS used to close over loop iterators when defining functions within the comprehension, but it lead to sometimes very complex compilations, and would be equally unexpected behaviour for someone expecting our current, more straightforward compilation. Recommended style is now:

comprehended = ((do (k = i) -> -> alert k) for i in [0..10])

or

comprehended = ((do (i) -> -> alert i) for i in [0..10])

or

comprehended = (((i) -> -> alert i)(i) for i in [0..10])

@lsb
Copy link
Author

lsb commented Apr 9, 2012

Oh, no question, lexical scope makes for less straightforward compilation, compared to dynamic scope; I just assumed that the scoping rules would be consistently lexical. Do you happen to remember where the commit to change that was? That might be interesting to see.

@michaelficarra
Copy link
Collaborator

See #1271, #959, #423.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants