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?
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:
… you could also be writing this, with the exact same result:
… or even:
… further equivalent changes:
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.