Y-Combinator in C#
Programming, Technologies ·For last few days, I was trying to use lambda feature of C# to implement Y-Combinator. After few trial and errors, I was able to implement it in C# 3.5. I’m currently posting the code here and in my next blog, I’ll explain how I derived it. In this code, Y-Combinator function, is used to implement anonymous recursive-factorial function called ‘factorial’.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YCombinator
{
class Program
{
delegate Func RecursiveFunction(RecursiveFunction f);
static void Main(string[] args)
{
Func, Func>, Func> Y = (f) =>
{
RecursiveFunction function = (h) =>
{
return (x) =>
{
return f(h(h))(x);
};
};
return function(function);
};
Func factorial = Y(function=>
{
return x =>
{
return x == 0 ? 1 : x * function(x - 1);
};
});
Console.WriteLine(factorial(5));
Console.ReadLine();
}
}
}