3 ms·
Maintaining state was just one example. See my other comment [0] for others. Regardless, you can't maintain state with closures in a pure language. You could c
by pka 10y ago
Maintaining state was just one example. See my other comment [0] for others.
Regardless, you can't maintain state with closures in a pure language. You could close over some local "variable", but that variable would be immutable. In an impure language that would work, but then you're back to managing global state, even if that state is not defined at the top level (i.e. global in the sense that different closures could still have access to the same piece of state, concurrently).
[0] https://news.ycombinator.com/item?id=13965917 https://news.ycombinator.com/item?id=13965917
EDIT: just to clarify, monads manage state purely. I.e, instead of writing:
function statefulFunction(state) {
(a, state1) = f(state);
(b, state2) = g(a, state1);
(c, state3) = h(b, state2);
return (c, state3);
}
you can write:
statefulFunction = do
a <- f
b <- g a
c <- h b
return c
But the resulting function is still pure, i.e. (state) => (c, state).