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

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

问题描述

现在似乎有不少主流语言支持函数字面量.它们也被称为匿名函数,但我不在乎它们是否有名字.重要的是,函数字面量是一个表达式,它产生一个尚未在其他地方定义的函数,因此例如在 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.

编辑添加:如果你有一个真正的函数文字表达式,你应该能够将它传递给一个函数f() 或立即将其应用于参数,即.(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).

我很好奇哪些语言可以让您编写递归的函数字面量.维基百科的匿名递归"文章没有给出任何编程示例.

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.

    还有其他的吗?

    推荐答案

    大多数语言通过使用Y 组合子.这是 Python 中的示例(来自 cookbook):

    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天全站免登陆