哪些语言支持*递归*函数文字/匿名函数? [英] Which languages support *recursive* function literals / anonymous functions?

查看:121
本文介绍了哪些语言支持*递归*函数文字/匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如今,似乎有很多主流语言支持函数文字.它们也称为匿名函数,但是我不在乎它们是否有名称.重要的是函数字面量是一个表达式,它产生的函数在其他地方尚未定义,因此例如在C中,&printf不计数.

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 thing is that a function literal is an expression which yields a function which hasn't already been defined elsewhere, so for example in C, &printf doesn't count.

编辑要添加:如果您具有真正的函数文字表达式<exp>,则应该能够将其传递给函数f(<exp>)或立即将其应用于参数,即. <exp>(5).

EDIT to add: if you have a genuine function literal expression <exp>, you should be able to pass it to a function f(<exp>) or immediately apply it to an argument, ie. <exp>(5).

我很好奇哪种语言可以让您编写递归的函数文字. Wikipedia的"匿名递归"文章没有提供任何编程示例.

I'm curious which languages let you write function literals which are recursive. Wikipedia's "anonymous recursion" article doesn't give any programming examples.

让我们以递归阶乘函数为例.

Let's use the recursive factorial function as the example.

这是我认识的人:

  • JavaScript/ECMAScript可以通过callee做到这一点:

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

  • 使用letrec语言很容易,例如Haskell(将其称为let):

  • it's easy in languages with letrec, eg Haskell (which calls it let):

    let fac x = if x<2 then 1 else fac (x-1) * x in fac

    ,并且在Lisp和Scheme中具有等效项.请注意,fac的绑定是表达式的局部内容,因此整个表达式实际上是一个匿名函数.

    and there are equivalents in Lisp and Scheme. Note that the binding of fac is local to the expression, so the whole expression is in fact an anonymous function.

    还有其他人吗?

    推荐答案

    大多数语言通过使用烹饪书):

    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
    

    这篇关于哪些语言支持*递归*函数文字/匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆