scotfl.ca

Pseudo-functional C

print( plus(&ten, &three) ); print( times(plus(times(&two, &three), four_fn), &ten) );

Result:

13
100

Reverse Polish Notation and a plethora of parentheses does not a functional language make. But they do impart a superficial resemblance. However, add a little context and suddenly it becomes a lot more ugly:

#include "functional.h"
#include "integers.h"


DType* plus (DType* a, ...)
{
    TWO_ARGS_ATOMIZED(a, b)
    return new_atom(a->atom + b->atom);
}


DType* times (DType* a, ...)
{
    TWO_ARGS_ATOMIZED(a, b)
    return new_atom(a->atom * b->atom);
}


DType* _four (DType *a, ...)
{
    return new_atom(4);
}


int main (int argc, char* argv[])
{
    DType* four_fn = new_nonatom(&_four);
    print( plus(&ten, &three) );
    print( times(plus(times(&two, &three), four_fn), &ten) );
}

This really needs lists and the usual suspects (car, cdr, cons, map, filter, and reduce). As well as some sort of call(List(fn, arg1, ...)), which I am pretty sure is as close to functional notation as I can get. As a bonus, lists will allow me to drop the varargs magic. Maybe I’ll add that next weekend. I had forgotten how much fun C can be, it was nice to go back to it for a while.

Git repo here.

This entry was posted on 13 April 2008 at 14:25 and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

One Response to “Pseudo-functional C”

  1. scotflApril 13th, 2008 at 16:00

    Actually, now that I think about it L(&print, L(&add, &one, &two)); should be entirely doable. Which is both clean, and frightening. C is awesome.