[Haskell-cafe] Functions are first class values in C
Peter Verswyvelen
bf3 at telenet.be
Sat Dec 22 09:48:51 EST 2007
Cristian Baboi wrote
> Lazy constant in C:
> int C1 (){ return 7; }
Not really, this is not lazy, since it always recomputes the value "7".
To have "lazy" values in C you would have to do something like:
struct ValueInt
{
int IsComputed;
union
{
int Value;
struct
{
int (*ComputeValue)(void *args);
void* Args;
};
};
};
int GetLazyInt (ValueInt* v)
{
if( !v->IsComputed )
{
v->Value = v->ComputeValue(v->Args);
v->IsComputed = true;
}
return v->Value;
}
But this of course, is totally useless in C and very bulky. It's also impossible to know when to call freemem on the Args (hence garbage collection in FP), when *not* to use lazy values but strict values instead (hence strictness analysis in FP), etc...
I must say I had the same opinion as you had for many many years. I always thought "functions as first class values" where just function pointers, so what is it these Haskell/FP guys are so excited about? But if you dig deeper, you'll see the magic... Notice you will have to give yourself some time; it is very hard to get out of the imperative blob. E.g. I'm still being sucked into the imperative blob after my first year of Haskell hacking :)
PS: As I'm relatively new to Haskell, don't take the above C code too seriously; it certainly will not reflect the way a real Haskell system works.
Peter
More information about the Haskell-Cafe
mailing list