Mar 15, 2008

CPS : Continuation Passing Style

I write a code using recursion.

static int Fact(int n)
{
if (n == 0)
{
return 1;
}
else
{
return n * Fact(n - 1);
}
}


I write a code using CPS.

static int FactCPS(int n, Func cont)
{
if (n == 0)
{
return cont(1);
}
else
{
return FactCPS(n - 1, a => cont(n * a));
}
}

static int Fact(int n)
{
return FactCPS(n, a => a);
}

No comments: