Which languages support *recursive* function literals / anonymous functions?

后端 未结 16 2151
一整个雨季
一整个雨季 2021-02-04 05:09

It seems quite a few mainstream languages support function literals these days. They are also called anonymous functions, but I don\'t care if they have a name. The important th

16条回答
  •  爱一瞬间的悲伤
    2021-02-04 05:46

    C#

    Reading Wes Dyer's blog, you will see that @Jon Skeet's answer is not totally correct. I am no genius on languages but there is a difference between a recursive anonymous function and the "fib function really just invokes the delegate that the local variable fib references" to quote from the blog.

    The actual C# answer would look something like this:

    delegate Func Recursive(Recursive r);
    
    static Func Y(Func, Func> f)
    {
        Recursive rec = r => a => f(r(r))(a);
        return rec(rec);
    }
    
    static void Main(string[] args)
    {
        Func fib = Y(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
        Func fact = Y(f => n => n > 1 ? n * f(n - 1) : 1);
        Console.WriteLine(fib(6));                          // displays 8
        Console.WriteLine(fact(6));
        Console.ReadLine();
    } 
    

提交回复
热议问题