Path: bambam.cs.iastate.edu!leavens Date: 16 Nov 93 15:29:26 GMT Message-ID: Newsgroups: isu.coms.227 Subject: Re: Closures and other languages (C) Keywords: closures, lambda, C Distribution: isu References: In leavens@cs.iastate.edu (Gary Leavens) writes: >I was talking to Dennis Ritchie (:-) about functions like curried+ > (define cadd > (lambda (x) > (lambda (y) > (+ x y)))) >and he claimed that you could do the same thing in C. >Dennis and his problem with the variable "x" point out the value >of Scheme's closures. The thing is that (cadd 2) in Scheme >is a closure, and so automatically keeps track of the binding >of x to 2. If we work out Dennis's problem with "x" we can see >even more of the value of closures in Scheme. Consider the >following: >typedef int (*func)(); >typedef struct {func f; int x} x_closure_struct, *closure; >int add(x,y) > int x,y; >{ return(x + y); } >closure cadd(x) > int x; >{ > closure c; > c = (closure) malloc(sizeof(x_closure_struct)); > /* ignoring the check for NULL */ > c->f = add; > c->x = x; > return(c); >} >int invoke_closure(c, arg) > closure c; > int arg; >{ return((c->f)(c->x,arg)); } >main() >{ printf("%i\n", invoke_closure(cadd(2),3)); } >To summarize, lambda builds closures in Scheme. >And a closure is a function + an environment. I heard from Bjarne Stroustrup about this too (:-). He pointed out that you could do the same thing in C++ by making a class for each closure. Indeed, the semantics of classes, as noted by Cook and others are closures. See chapter 12 of our book for why this is. Here's how we could do what was done in C using C++. class cadd { private: int x; public: cadd (int z) : x(z) {} invoke (int y) { return x + y; } }; // The main program might look like... #include void main() { cout << cadd(2).invoke(3) << endl; } This prints 5. The point here is that the idea of closures is a very powerful one. You can even use it in C++, to understand classes and objects. Essentially, a class in C++ is a function that returns a record (C++ struct) containing functions. These functions share a common environment, which is the struct, including the data members like x in cadd. Gary