Y combinator: Difference between revisions
Content deleted Content added
→{{header|C sharp}}: Added translation of Go |
→{{header|C sharp}}: Added translation of Swift |
||
Line 1,100: | Line 1,100: | ||
Recursive: |
Recursive: |
||
<lang csharp> static Func Y(FuncFunc f) => x => f(Y(f))(x);</lang> |
<lang csharp> static Func Y(FuncFunc f) => x => f(Y(f))(x);</lang> |
||
====[http://rosettacode.org/mw/index.php?oldid=287744#Swift Swift]==== |
|||
<code>T -> TResult</code> in Swift corresponds to <code>Func<T, TResult></code> in C#. |
|||
'''Verbatim''' |
|||
The more idiomatic version doesn't look much different. |
|||
<lang csharp>using System; |
|||
static class Program { |
|||
struct RecursiveFunc<F> { |
|||
public Func<RecursiveFunc<F>, F> o; |
|||
} |
|||
static Func<A, B> Y<A, B>(Func<Func<A, B>, Func<A, B>> f) { |
|||
var r = new RecursiveFunc<Func<A, B>> { o = w => f(_0 => w.o(w)(_0)) }; |
|||
return r.o(r); |
|||
} |
|||
static void Main() { |
|||
// C# can't infer the type arguments to Y either; either it or f must be explicitly typed. |
|||
var fac = Y((Func<int, int> f) => _0 => _0 <= 1 ? 1 : _0 * f(_0 - 1)); |
|||
var fib = Y((Func<int, int> f) => _0 => _0 <= 2 ? 1 : f(_0 - 1) + f(_0 - 2)); |
|||
Console.WriteLine($"fac(5) = {fac(5)}"); |
|||
Console.WriteLine($"fib(9) = {fib(9)}"); |
|||
} |
|||
}</lang> |
|||
Without recursive type: |
|||
<lang csharp> public static Func<A, B> Y<A, B>(Func<Func<A, B>, Func<A, B>> f) { |
|||
Func<dynamic, Func<A, B>> r = z => { var w = (Func<dynamic, Func<A, B>>)z; return f(_0 => w(w)(_0)); }; |
|||
return r(r); |
|||
}</lang> |
|||
Recursive: |
|||
<lang csharp> public static Func<In, Out> Y<In, Out>(Func<Func<In, Out>, Func<In, Out>> f) { |
|||
return x => f(Y(f))(x); |
|||
}</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |