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

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

    Most languages support it through use of the Y combinator. Here's an example in Python (from the cookbook):

    # Define Y combinator...come on Gudio, put it in functools!
    Y = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda arg: f(f)(arg)))
    
    # Define anonymous recursive factorial function
    fac = Y(lambda f: lambda n: (1 if n<2 else n*f(n-1)))
    assert fac(7) == 5040
    

提交回复
热议问题