Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are closures a violation of the functional programming paradigm?

Functional programming "avoids state and mutable data".

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

How is Haskell purely-functional if it supports closures? Don't they break referential transparency?

like image 375
kwarrick Avatar asked Feb 23 '12 18:02

kwarrick


2 Answers

In Haskell, closures have free variables in the same way that in math you can write f x = x^2 - it doesn't mutate state.

I would say that Haskell avoids mutable state.

like image 119
amindfv Avatar answered Oct 14 '22 06:10

amindfv


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.

like image 19
Luis Casillas Avatar answered Oct 14 '22 05:10

Luis Casillas