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

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

    You can do it in Perl:

    my $factorial = do {
      my $fac;
      $fac = sub {
        my $n = shift;
        if ($n < 2) { 1 } else { $n * $fac->($n-1) }
      };
    };
    
    print $factorial->(4);
    

    The do block isn't strictly necessary; I included it to emphasize that the result is a true anonymous function.

提交回复
热议问题