Created
July 13, 2016 13:23
-
-
Save MikeMKH/9041d0f6d39962adc661e267f0248be4 to your computer and use it in GitHub Desktop.
C# 4 "Local Function" example with tuples in a tail call
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pairs with https://gist.github.com/MikeMKH/f5e2bf37b384308d25d54793d9e4f752