Closures (in Haskell)

2019-03-12 16:34发布

问题:

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?

回答1:

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.



回答2:

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.