3 ms·
> The closure f does not capture the value of i at the time when f is defined, changing i after f was defined make nonsense of the idea of a closure. I have an
by iraphael 11y ago
> The closure f does not capture the value of i at the time when f is defined, changing i after f was defined make nonsense of the idea of a closure.
I have an incomplete understanding of functional programming. Are there other uses for closures (besides readability and practicality) that still work if they don't capture the value of i? If not, is this something someone should suggest as a change in swift-evolution?
- wtetzner 11y ago> The closure f does not capture the value of i at the time when f is defined, changing i after f was defined make nonsense of the idea of a closure. Not sure why this "makes nonsense of the idea of a closure." You're closing over variables, not values. If you marked i using let instead of var, then you'd get the "preferred" behavior.
- hellofunk 11y agoThis underscores the notion that functional programming is ultimately about immutability, and all the idioms expected by a truly functional language are really a result of how it handles state more than anything. A closure is usually expected to close over values, and the idea of a "variable" doesn't really mean the same in a truly functional language, which is where all the confusion and the pain points stem from.
- wtetzner 11y agoYes, if you come from functional languages then you might expect to close over values, but I don't think that in general "a closure is expected to close over values". In particular, both Scheme and Common Lisp close over variables, not values. JavaScript also closes over variables, so it's not just "obscure" languages that behave this way. Java only allows you to close over variables that are effectively final, to remove confusion on both sides (e.g. why doesn't the value in my closure change when I manipulate the original variable? vs. why does my the value in my closure change when I manipulate the original variable?)
- tel 11y agoHe's complaining about mutable state, essentially. The function `f` captures reference to `i` but does so transparently. One might expect that `f` would be free of side effects, but since `i` can be re-bound whenever this is not the case. Essentially it comes down to the semantics of `=` whether it's declaration or assignment. Swift appears to choose it to be assignment. If I remember right you can declare things constant which would effect declaration only (sort of) but clearly there's an expectation that this happens all the time.
- masklinn 11y ago> He's complaining about mutable state Bindings rather than state, the author has no issue with captured objects being mutable, only with the captured environment being mutable.