mjd-phillylambda on 15 Mar 2010 13:35:30 -0700


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: closures


> So I'd like to test my understanding with this group...
> 
> 	int x;
> 
> 	void foo(int x);
> 	void baz(void (*F)(void));
> 
> 	void callback(void)
> 	{
> 		foo(x);
> 	}
> 
> 	void bar(void)
> 	{
> 		baz(&callback);
> 	}
> 
> C doesn't "support" closures, but the code above has one.

Only in a trivial sense.  C doesn't support nested function scopes, so
in C one can't construct an interesting example of closures or of
their failure in C.  I wanted to construct a C example for you, but
none of my constructions made sense as C.

To not-answer your question:

> The above is a closure, if you could do such a thing in C. 

I think the only thing you could usefully do with this question is to
unask it.  Trying to understand closures by studying the non-behavior
of the nonexistent closures of C is pointless.

If you like Perl, I suggest that you read chapter 3 of "Higher-Order
Perl", available for free download at:

        http://hop.perl.plover.com/

I think the explanation there is both clear and rigorous.

If you like some other language that has closures, I suggest you ask
for an example in that language.

If you only like C, I suggest you either forget about closures
(because C doesn't have them) or learn to like some language that does
have them.

> The word closure
> is used here because we create an instance of foo() over which x is "closed".
> 
> Do I have it right so far?

No:

* You have not created an instance of foo, or indeed of anything.
  Functions always have static duration in C.  Instances of functions
  are created at compile time, and not afterward.

* The jargon is that the function is closed over the variable, not the
  other way around.

> I would appreciate it if someone could propose a few problems which
> are trivial to solve with closures, but difficult without.

a. Implement an object-oriented programming system.  Closures make
   adequate objects.  This is discussed in detail in _Structure and
   interpretation of Computer Programs_, should you want to know more.

b. Almost anything in _Higher-Order Perl_; see the table of contents.





  • Follow-Ups:
    • Re: closures
      • From: Michael Bevilacqua-Linn <michael.bevilacqualinn@gmail.com>
    • Re: closures
      • From: "Mark M. Hoffman" <mhoffman@lightlink.com>
  • References:
    • closures
      • From: "Mark M. Hoffman" <mhoffman@lightlink.com>