Skip to content

Instantly share code, notes, and snippets.

@cburgdorf
Created November 19, 2011 19:59
Show Gist options
  • Save cburgdorf/1379283 to your computer and use it in GitHub Desktop.
Save cburgdorf/1379283 to your computer and use it in GitHub Desktop.
Functional recursion and tail recursion
using System;
namespace Factorial
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("factorial of 3 using simple recursion: " + Factorial(3));
Console.WriteLine("factorial of 3 using accumulator passing style: " + FactorialAcc(3));
Console.WriteLine("factorial of 3 using continuation passing style: " + FactorialCps(3));
Console.ReadLine();
}
/// <summary>
/// This function calculates the factorial of the given number using a naive approach
/// </summary>
public static int Factorial(int number)
{
return number == 0 ? 1 : number * Factorial(number - 1);
}
/// <summary>
/// This function calculates the factorial of the given number using a tail recursive approach, namely accumulator passing
/// </summary>
public static int FactorialAcc(int number)
{
Func<int, int, int> acc = null;
acc = (val, accVal) => val == 0 ? accVal : acc(val - 1, accVal * val);
return acc(number, 1);
}
/// <summary>
/// This function calculates the factorial of the given number using a tail recursive approach, namely continuation passing
/// </summary>
public static int FactorialCps(int number)
{
Func<int, Func<int, int>, int> cps = null;
cps = (val, continuation) => val == 0 ? continuation(1) : cps(val - 1, y => continuation(val*y));
return cps(number, y => y);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment