Thursday, November 10, 2011

C Style Haskell

The other day I found this blog post on using GADTs to write more usable C style Haskell with effects, references and loops.  I couldn't get the example to typecheck without unsafe code, so I decided to write my own version.  I wanted the behavior of expressions and operators to be similar to that of C.  This is what I came up with:

swap(r1, r2) = function $ do
{
    z <- auto undefined;
    z =: r1;
    r1 =: r2;
    r2 =: z;
};

factorial = function $ do
{
    a <- auto 0;
    n <- auto 1;
    for ( a =: prim 1 , a <. prim 11 , a +=: prim 1 ) $ do
    {
       n *=: a;
       iff ( a <. prim 7) $ do
       {
           continue;
       };

       iff ( a >. prim 5) $ do
       {
            break;
       };
    };

    swap( ref n , ref a);
    returnF n;
};

In order to make expression operators behave similarly to that of C, I added a new value type as a wrapper for computations in this monad, so as to allow seamless composition of effectfull expressions on the right hand side.  "callCC" was used to achieve C style "break", "continue" and "return".  The reader monad was used to hide the extra arguments required for callCC.

Here is the full code.