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

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

    You've mixed up some terminology here, function literals don't have to be anonymous.

    In javascript the difference depends on whether the function is written as a statement or an expression. There's some discussion about the distinction in the answers to this question.

    Lets say you are passing your example to a function:

    foo(function(n){if (n<2) {return 1;} else {return n * arguments.callee(n-1);}});
    

    This could also be written:

    foo(function fac(n){if (n<2) {return 1;} else {return n * fac(n-1);}});
    

    In both cases it's a function literal. But note that in the second example the name is not added to the surrounding scope - which can be confusing. But this isn't widely used as some javascript implementations don't support this or have a buggy implementation. I've also read that it's slower.

    Anonymous recursion is something different again, it's when a function recurses without having a reference to itself, the Y Combinator has already been mentioned. In most languages, it isn't necessary as better methods are available. Here's a link to a javascript implementation.

提交回复
热议问题