Are closures a violation of the functional programming paradigm?

前端 未结 4 1438
伪装坚强ぢ
伪装坚强ぢ 2021-01-31 18:32

Functional programming \"avoids state and mutable data\".

Closures hide state by binding their lexical environment and are thus closed over their free variables

4条回答
  •  梦如初夏
    2021-01-31 18:36

    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 IORefs 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.

提交回复
热议问题