Functional programming \"avoids state and mutable data\".
Closures hide state by binding their lexical environment and are thus closed over their free variables
No, closures are fine and don't cause problems in Haskell because a closure closes over the values of the free variables. The reason you can hide state behind closures in other languages is that you close over the reference. As you know, in Javascript:
var x = 1;
var f = function(y) { return y + x; }
f(2) // => 3
x = 2;
f(2) // => 4
You can actually model this by using IORef
s in Haskell:
main = do
x <- newIORef 1
let f y = do x' <- readIORef x
return (y + x')
r1 <- f 2
writeIORef x 2
r2 <- f 2
This is OK because function f
has type Int -> IO Int
rather than Int -> Int
. In other words, f
is bound to the same action, but when executed that same action may return different results each time.