Are closures a violation of the functional programming paradigm?

前端 未结 4 1496
伪装坚强ぢ
伪装坚强ぢ 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:58

    Closures are not a violation because all bindings in Haskell are immutable. What closures really mean is that a lambda with free variables doesn't denote one unique function; it will denote different functions depending on the bindings that are in effect for its free variables when each time it is evaluated. E.g.:

    makeClosure :: Num a => a -> a -> a
    makeClosure x = \y -> x+y
    

    The expression makeClosure 5 evaluates to a different function than makeClosure 6; and much more importantly, two occurrences of makeClosure 5 in different parts of the program evaluate to the same function, as does makeClosure (2+3) or similar; i.e., we have referential transparency (substituting expressions with their equals preserves the meaning of a program).

    You seem to be confused over the meaning of "state" in the quote you mention. State in this context means mutable data; closures can definitely "hide" data, but in Haskell this data is not mutable, so it doesn't hide state. As a contrast to this, in my experience Java programmers often say that a class instance "hides state" in cases where the data in question is not mutable, e.g., assigned to a private final instance field from the constructor; what they really mean is that classes (and closures) encapsulate data.

提交回复
热议问题