[Haskell-beginners] Re: Closure

Daniel Fischer daniel.is.fischer at web.de
Sat Aug 15 12:31:14 EDT 2009


Am Samstag 15 August 2009 18:07:08 schrieb Daniel Bastos:
> In article <h65p0h$rjl$1 at ger.gmane.org>,
>
> 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?
>
> > Reduction to weak head normal form yields
> >
> >    foo = let x = 3 in \y -> x + y
> >
> > which means that  foo  is a function  \y -> x + y  paired with the value
> > of the free variable  x .
>
> I see.
>
> > 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?
>

You can't do

cmp :: a -> a -> a -> Ordering
cmp pivot x y = ...

funkyFun :: (a -> a -> a -> Ordering) -> [a] -> [a]
funkyFun _ [] = []
funkyFun c (x:xs) = x:sortBy (c x) xs

main = do
    args <- getArgs
    print $ funkyFun cmp (some pseudorandom list depending on args)

in C (at least not without some black magic).

The plus3 example is a "closure" which is hardcoded and available at compile time.
I think, to say that a language allows closures means it allows closures determined at run 
time.


More information about the Beginners mailing list