Last active
August 29, 2015 14:13
-
-
Save SLaks/918b5ae1cc148c86785a to your computer and use it in GitHub Desktop.
LINQ Y Combinator
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
static void Main() { | |
var fibonacci = from fib in YCombinate<ulong, ulong>.Definition | |
select n => n < 2 ? 1 : fib(n - 1) + fib(n - 2); | |
Console.WriteLine(fibonacci(5)); | |
} | |
delegate TDelegate Recursive<TDelegate>(TDelegate r); | |
static class YCombinate<TArg, TReturn> { | |
public static class Definition { | |
public static Func<TArg, TReturn> Select(Recursive<Func<TArg, TReturn>> definition) { | |
Func<TArg, TReturn> retVal = null; | |
retVal = arg => definition(retVal)(arg); | |
return retVal; | |
} | |
} | |
} |
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
var fibonacci = from def in new Func<Func<ulong, ulong>, Func<ulong, ulong>>[] { | |
fib => n => n < 2 ? 1 : fib(n - 1) + fib(n - 2) | |
} | |
let ret = new Func<ulong, ulong>[] { null } | |
select ret[0] = a => def(ret[0])(a); | |
Console.WriteLine(fibonacci.First()(5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment