Subject: Can't I make closures in C?
Date: 2 Mar 95 04:24:18 GMT
Newsgroups: isu.coms.541

I've been hearing some fuss about "lambda" and "fn" and I just don't
get it.  What's the big deal?  I can do all this in my favorite
langauge: C.  For example, consider everybody's favorite
example of a curried function in SML, which is the following
curried version of +.

	(* curried addition in (desugared) SML *)
	val cadd = (fn x => (fn y => x + y));

For example, ((cadd 2) 3) returns 5.

But in C, functions are objects too, and I can pass around function
pointers.  So consider the following program to do curried addition.

	/* curried addition program in ANSI C */
	#include <stdio.h>

	typedef int (*func)(int);  /* functions that take and return ints */

	int takes_y(int y) { return(x + y); }

	func cadd(int x) { return(&takes_y); }

	int main() { printf("%i\n", (cadd(2))(3)); }

I just about have this working, and it seems like it does the
same thing as the SML code.  (Only problem is that the variable
"x" used in "takes_y" is undefined, but I'll fix that soon.)
Doesn't this prove that SML, and "fn" are no big deal?
Who cares anyway?

	Dennis Ritchie

--
	AT&T Bell Labs
	Murray Hill
	New Jersey