Do we need fixed point compilers in C #?

I played with recursive lambdas in C # and found two approaches to do this on the Internet. One approach uses a fixed point combinator , while the other does not. In the code below, f1 is built using combinator, and f2 is defined directly. My question is do we need fixed-point compilers in C # or does the language already provide everything we need, so we can leave them alone?

class Program
{
    static Func<T, T> F<T>(Func<Func<T,T>,Func<T,T>> f)
    {
        return x => f(F(f))(x);
    }

    static void Main(string[] args)
    {
        Func<Func<int,int>,Func<int,int>> f = fac => x => x == 0 ? 1 : x * fac(x - 1);
        var f1 = F(f);

        Console.WriteLine(f1(5));

        Func<int, int> f2 = null;
        f2 = x => x == 0 ? 1 : x * f2(x - 1);

        Console.WriteLine(f2(5));
    }
}
+3
source share
4 answers

As we can give a name to the method, this means that the language already has the necessary support for the recursion built into it.

, , , , "" . Y-combinator , , , . # : 1. null 2. (, ).

+4

, Recursive :

public static class Recursive {
            public static Func<R> Func<R>(
                Func<Func<R>, Func<R>> f) { 
                return () => f(Func(f))(); }
            public static Func<T1, R> Func<T1, R>(
                Func<Func<T1, R>, Func<T1, R>> f) { 
                return x => f(Func(f))(x); }
            public static Func<T1, T2, R> Func<T1, T2, R>(
                Func<Func<T1, T2, R>, Func<T1, T2, R>> f) {
                return (a1, a2) => f(Func(f))(a1, a2);
            }
            //And so on...
        }

class Program {

    static void Main(string[] args) {

        Console.WriteLine(
            Recursive.Func<int, int>(factorial =>
                x => x == 0 ? 1 : factorial(x - 1) * x
            ) 
            (10)
        );

        Console.WriteLine(
            Recursive.Func<int,int,int>(gcd =>
                (x,y) => 
                    x == 0 ? y:
                    y == 0 ? x:
                    x > y  ? gcd(x % y, y):
                    gcd(y % x, x)
            )
            (35,21)
        );
    }
}
+3

Func :

static Func<int, int> Factorial = (n) => n <= 1 ? 1 : n*Factorial(n - 1);
+1

""? # , #. .

Remembering a recursive function is one place where you need a fixed-point combinator. Compare this in C # to Haskell .

So, before C # is “needed”, it takes a lot of work to make this kind of programming practical enough.

-2
source

Source: https://habr.com/ru/post/1706560/


All Articles