Mark M. Hoffman on 15 Mar 2010 14:43:24 -0700 |
Hi: * mjd-phillylambda@plover.com <mjd-phillylambda@plover.com> [2010-03-15 16:35:05 -0400]: > > > 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. Fair enough. > 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. What would a closure look like in C if it had them? Mu. Got it. ;) (http://www.io.com/~snewton/zen/mu.html) > 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. Thank you; I'll look there. > 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. All of us C programming dinosaurs are alike eh? ;) > > 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. Yes of course. My second example was just a hypothetical in a C-like syntax, if you will. It isn't my intention to re-invent them in C. I only wanted to see if I understand the concept itself. > * The jargon is that the function is closed over the variable, not the > other way around. Oops - thank you. > > 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. This is trivial? I.e. 2-3 screenfuls of code in an hour or so? > b. Almost anything in _Higher-Order Perl_; see the table of contents. Thanks & regards, -- Mark M. Hoffman mhoffman@lightlink.com
|
|