Subject: Re: OT: O'Caml (was: LISP - When you've seen it, what else can impress?)
From: rpw3@rpw3.org (Rob Warnock)
Date: Tue, 10 Sep 2002 15:32:27 -0000
Newsgroups: comp.lang.lisp
Message-ID: <uns44bbhh26id6@corp.supernews.com>
Matthew Danish  <mdanish@andrew.cmu.edu> wrote:
+---------------
| > I personally never had much use for programs in language X that generate 
| > programs in language X, especially if language X has higher-order 
| > functions, but maybe others can't live wihtout it.
| 
| C programmers get by without higher-order functions. (somehow)
+---------------

C supports higher-order functions. In fact, they're used quite
heavily in the Unix kernel code (well, at least in Irix, though
AFAIK the code I'm thinking of also exists in BSD) to do stuff
like MzScheme's "hash-table-for-each" or CL's "maphash", not to
mention the ubiquitous use in GUIs of functions which accept other
"callback" functions as arguments.

What C doesn't have built-in is *closures*! As a result, HOFs in C
almost universally resort to faking it with a separate argument to
the HOF which is an opaque cookie to be passed to one of the other
arguments, itself a function. So instead of CL's "maphash" signatures:

    (maphash function hash-table) => nil
      where: (function key value) => nil

you end up with something like this:

    void
    walkhash (ht_t table,
	      void (*fcn)(ht_t table, void *cookie, void *key, void *value),
	      void *cookie);

where the "walkhash" HOF calls the argument function with not only
the key/value pair, but actually *two* (in this case) pieces of data
that would in Scheme or Lisp normally be closed-over lexicals. [Two,
since otherwise the caller would have to allocate some memory to pack
them into, to get a single handle.]

Note that with a lot of hackery on the cookie (i.e., effectively
making the cookie be a dynamically-allocated "environment" frame)
you *can* even get the effect of nested closures or closures over
larger numbers of variables, but it's ugly.


-Rob

-----
Rob Warnock, PP-ASEL-IA		<rpw3@rpw3.org>
627 26th Avenue			<URL:http://www.rpw3.org/>
San Mateo, CA 94403		(650)572-2607