这里有一些不同语言的片段。
有问题的函数 double
取自 SICP,例如。 1.41.
口齿不清:
(define (double f) (lambda (x) (f (f x))))
(define (inc x) (+ x 1))
(((double (double double)) inc) 5)
python :
def double(f):
def result(x):
return f(f(x))
return result
def inc(x):
return x + 1
double(double(double(inc)))(5)
Javascript:
var double = function(f) {
return function(x) { return f(f(x)) };
};
var inc = function(x) { return x + 1 };
(double(double(double(inc))))(5);
ruby :
double = lambda {|f| lambda {|x| f[f[x]] } }
inc = lambda {|x| x+1 }
double[double[double[inc]]][5]
如果我没疯的话,这些函数应该做同样的事情并返回同样的结果。 但是,lisp 版本返回 21,而其他版本返回 13。您能向我解释一下这种区别吗?我错过了什么吗?
最佳答案
在方案代码中调用函数的方式与其他方式不同。等效的 python 将是:
double(double(double))(inc)(5)
换句话说,方案代码创建了一个函数,该函数应用了另一个函数 16 次,并将该函数应用于 inc
。 python 创建了应用 inc
8 次的函数;其他的和 python 一样。
如果您为中间步骤引入名称,区别可能会更清楚一些。在方案中:
(define quadruple (double double))
(define hexadecuple (double quadruple)) ; hexadecuple may not actually be a word...
(define add16 (hexadecuple inc))
(add16 5)
我希望这是正确的语法;我已经有一段时间没有用 scheme 做过任何事情了。
在 python 中:
add2 = double(inc)
add4 = double(add2)
add8 = double(add4)
add8(5)
关于javascript - 语言之间递归处理的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8136559/