Wednesday, 16 December 2009

C# Continuation Monad



using System;


public static class ContinuationMonad
{
    public static Func<Func<V, R>, R> SelectMany<T, U, V, R>(
             this Func<Func<T, R>, R> m,
                  Func<T, Func<Func<U, R>, R>> f,
                  Func<T, U, V> p)
    {
        return c => m(a => f(a)(x => c(p(a, x))));
    }

    public static Func<Func<T, R>, R> Return<T, R>(this T x)
    {
        return k => k(x);
    }

}

public class Program
{
    public static void Main()
    {
        Func<int, Func<Func<int, int>, int>> facCont = null;
        facCont = n => n == 0 ? 1.Return<int, int>()
                          : from x in n.Return<int, int>()
                            from y in facCont(x - 1)
                            select x * y;

        Func<int, int> fac = n => facCont(n)(x => x);


        Console.WriteLine(fac(5));
    }
}

No comments: