Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created July 13, 2016 13:23
Show Gist options
  • Save MikeMKH/9041d0f6d39962adc661e267f0248be4 to your computer and use it in GitHub Desktop.
Save MikeMKH/9041d0f6d39962adc661e267f0248be4 to your computer and use it in GitHub Desktop.
C# 4 "Local Function" example with tuples in a tail call
using System;
namespace TupleExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"1! = {Factorial(1)}");
Console.WriteLine($"5! = {Factorial(5)}");
Console.WriteLine($"20! = {Factorial(20)}");
Console.ReadKey();
}
private static long Factorial(int x) => FactorialAux(new Tuple<int, int>(1, x));
private static long FactorialAux(Tuple<int, int> t)
{
if (t.Item2 <= 1) return t.Item1;
var r = new Tuple<int, int>(t.Item1*t.Item2, t.Item2 - 1);
return FactorialAux(r);
}
}
}
@MikeMKH
Copy link
Author

MikeMKH commented Jul 13, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment