[Haskell-beginners] Closure
Brent Yorgey
byorgey at seas.upenn.edu
Wed Jul 29 16:24:42 EDT 2009
On Wed, Jul 29, 2009 at 09:11:02PM +0100, Matthew J. Williams wrote:
>
>> Williams<matthewjwilliams1 at googlemail.com> wrote:
>> > Good morning
>> >
>> > What is a closure and, what purpose does it serve?
>>
>> This seems like a good explanation: http://www.haskell.org/haskellwiki/Closure
>>
>> /M
>>
>> Williams<matthewjwilliams1 at googlemail.com> wrote:
> How does a closure differ from a binding? An example or two would be nice. :-)
A closure is essentially a binding, *together with* the enclosing
environment---the idea being that the binding may refer (via free
variables) to things in its environment. The ability to have closures
is absolutely crucial to having first-class functions.
For example, consider this function:
mkAdder :: Int -> (Int -> Int)
mkAdder y = \x -> x + y
mkAdder takes an Int as an argument, and returns a function (Int ->
Int) as a result. But take a look at the function it returns: \x -> x
+ y has a free variable (y) which refers to its environment. So
really what you get when you call mkAdder with a particular argument
(say, 3) is a closure, containing the function \x -> x + y together
with the environment (y = 3).
Of course, hopefully you have realized that mkAdder is really just
(+), written in a funny way! So this isn't a contrived example;
closures are quite fundamental in Haskell.
With that said, on some level the idea of a closure is really just an
implementation detail---I wouldn't say that understanding it is of
fundamental importance in learning Haskell. But learning things never
hurts (except when it does).
Hope this helps!
-Brent
More information about the Beginners
mailing list