Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closures (in Haskell)

To me a Closure is a (nested?) function with co-located data.

When you write software in Haskell and look it through afterwards, you frequently find closures that you have created unintentionally.

I do not quite get this right for myself. In what situations would I intentionally want to code closures? After all, in all examples I find the amount of co-located data is trivial/small and thus it does not quite seem to me as if in practice that would ever justify their (intentional) creation. Is there any Haskell module that would support me in intentionally creating closures and e.g. storing them in a map?

like image 241
J Fritsch Avatar asked Jan 31 '12 22:01

J Fritsch


2 Answers

In Haskell, functions are an essential part of the language, largely because Haskell is based on the Lambda Calculus.

In the Lambda Calculus, there are functions that have "free variables", meaning that they use variables that were not passed as direct parameters to them. Functions with free variables are what you would call "closures" in this case.

Because functions with free variables are so common in LC, they also form an integral part of the Haskell language. For example, when you write this:

f a b c = a * b + c

... you could also be writing this, with the exact same result:

f a b = \ c -> a * b + c

... or even:

f a b = let product = a * b in \ c -> product + c

... further equivalent changes:

f a = \ b -> let product = a * b in \ c -> product + c

This is because Haskell essentially creates functions with free variables everywhere, and thus, closures are created all the time. Some of these might be optimized away by the compiler, but it is safe to assume that there will be more closures used than you might ever be able to discover on your own.

So, don't try to locate closures; they are nothing special in Haskell and are used all the time.

like image 165
dflemstr Avatar answered Sep 18 '22 12:09

dflemstr


Typically, if I need to precompute tables or something for a function, or there's a function that requires a lot of data, yeah, that'll be done as a closure. For example, on my AI homework the other day, I wrote a thing that learned from a lot of samples and then popped out a (Point -> Bool) function, but that function had to depend on a lot of data that I'd accumulated from the learning process.

like image 21
Louis Wasserman Avatar answered Sep 19 '22 12:09

Louis Wasserman