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

后端 未结 16 2100
一整个雨季
一整个雨季 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:57

    In C# you need to declare a variable to hold the delegate, and assign null to it to make sure it's definitely assigned, then you can call it from within a lambda expression which you assign to it:

    Func fac = null;
    fac = n => n < 2 ? 1 : n * fac(n-1);
    Console.WriteLine(fac(7));
    

    I think I heard rumours that the C# team was considering changing the rules on definite assignment to make the separate declaration/initialization unnecessary, but I wouldn't swear to it.

    One important question for each of these languages / runtime environments is whether they support tail calls. In C#, as far as I'm aware the MS compiler doesn't use the tail. IL opcode, but the JIT may optimise it anyway, in certain circumstances. Obviously this can very easily make the difference between a working program and stack overflow. (It would be nice to have more control over this and/or guarantees about when it will occur. Otherwise a program which works on one machine may fail on another in a hard-to-fathom manner.)

    Edit: as FryHard pointed out, this is only pseudo-recursion. Simple enough to get the job done, but the Y-combinator is a purer approach. There's one other caveat with the code I posted above: if you change the value of fac, anything which tries to use the old value will start to fail, because the lambda expression has captured the fac variable itself. (Which it has to in order to work properly at all, of course...)

提交回复
热议问题