Mark M. Hoffman on 15 Mar 2010 13:20:26 -0700


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

closures


Hi all:

I'm trying to refresh/relearn FP skills, most of which I'd quickly forgotten
after college (and 10+ years of almost all C/asm).

Initially I found closures to be confusing; but now I think that's only because
the term is thrown around without precision on many of the web pages I happened
to read about it.

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.  The function pointer
itself is not the closure... but the binding of foo() w/ the variable x in the
function callback() is almost it.  I say almost only because a true closure
would bind foo() to a value as opposed to a variable.

	void foo(int x);
	void baz(void (*F)(void));

	void bar(void)
	{
		baz( &(foo(42)) );	// invalid C code
	}

The above is a closure, if you could do such a thing in C.  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?

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

Thanks & regards,

-- 
Mark M. Hoffman
mhoffman@lightlink.com