[Haskell-beginners] Re: Closure

Heinrich Apfelmus apfelmus at quantentunnel.de
Sun Aug 16 09:58:33 EDT 2009


Daniel Bastos wrote:
> Heinrich Apfelmus wrote:
> 
>> The simplest example of a closure is indeed
>>
>>    foo = add 3
>>
>> where
>>
>>    add = \x y -> x + y
> 
> Question. This is actually equal to 
> 
> add x y = x + y
> 
> But you wrote in terms of \. Why such preference?

I wanted to emphasize that  add  is a value just like  4  or  "baz" ,
i.e. that it's not very different from writing say

    add = "baz"

>> Note that closures are an implementation detail. From a semantic point
>> of view,  add 3  can readily be understood as an ordinary function.
> 
> This makes sense. Because, even in a language like C, a similar effect
> can be achieved, no? For example
> 
> int plus(int x, int y) { return x + y; }
> 
> int plus3(int y) { plus(3, y); }
> 
> So, what I can't do in C, besides almost everything I can't do, is to
> do this nicely like I do in Haskell. But we don't call this a
> closure. In fact, we say C does not allow for closures. So what am I
> missing?

A litmus test for being a functional language is the ability to define
function composition

   f . g = \x -> f (g x)

This is not possible in C; mainly because functions cannot be defined
locally, they have to be declared at the top-level.

(I think this test is due to Lennart Augustsson, but I can't find a
reference on the web right now.)


Hm... this means that Brent's example

   foo x = add
       where
       add y = x + y

is actually a much better demonstration of a closure than the one I
gave. Yes, I think this one is impossible to write in C.


Regards,
apfelmus

--
http://apfelmus.nfshost.com



More information about the Beginners mailing list