Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need fixed point combinators in C#?

I was playing with recursive lambdas in C# and have found two approaches to do this on the web. One approach uses fixed point combinator and 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 combinators in C# or the language already provides all 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));
    }
}
like image 965
Prankster Avatar asked Feb 01 '26 17:02

Prankster


1 Answers

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

Note that the second method given in your question involves changing the value of a variable after it has been introduced, making it not "pure" functional programming. Y-combinator is only necessary if your system of functional calculus doesn't have a built-in notion of a function that can refer to its own definition by name before the definition is completely defined. C# has two ways to do that directly: 1. initially defining the function variable as null and 2. declaring an ordinary named method (by far the preferred technique).

like image 122
Daniel Earwicker Avatar answered Feb 04 '26 06:02

Daniel Earwicker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!