It's quite a cool trick for avoiding mutable global state, or clobbering the global namespace. It's used a lot in javascript projects.
function make_counter() {
var i = 0;
return (function() {
return i++;
});
}
var blah = make_counter();
every time you call `blah()` now, it will return the next number in the series, but there's no way for anywhere else in the application to modify `i`. This can be useful as an iterator, so giving you effectively the same as `yield`-ish generators in python.
I think the counter-argument is that all mutable state is bad, and the equivalent thing could be accomplished if invoking `blah` returned the next number in the series as well as a new closure that does the same thing.
Sure, everything as immutable does make certain guarantees about the code a lot easier. Also certain algorithms become very nice.
Purity is pretty awesome. I really like conceptual Haskell (actual real Haskell tends to become too abstract for my brain to remember important details when I come back to a project...).
The (sad) fact is that mutating a bit of state is actually often much faster, or a lot cleaner to read / understand than implementing a fully pure functional version. And by limiting access to state, you make sure you don't accidentally introduce dependencies.
Using closures like this, can end up being very similar to object-oriented code (in the best-case, strictly limited sense) whereby each area of concern in the code can only modify what you expect it to be able to modify, and you can be sure nowhere else in the code can access it.
is that really a good idea?