Here's Mathematica's Nest function Definition .什么是eqv。在 Ruby 中?
思路是这样的:
nest(f, x, 3) #=> f(f(f(x)))
最佳答案
您可以使用 inject
定义您自己的:
def nest(f, x, n)
n.times.inject(x) { |m| f.call(m) }
end
然后你可以这样调用它:
>> def f(x) 2*x end
>> nest(method(:f), 1, 3)
=> 8
如果你想返回一个函数(即不指定 x
),那么你可以返回一个 lambda:
def nestx(f, n)
->(x) { n.times.inject(x) { |m| f.call(m) } }
end
并像这样使用它:
>> nestx(method(:f), 3).call(1)
=> 8
或者您可以重新排列 nest
参数并使用 Proc#curry
:
def nest(f, n, x)
n.times.inject(x) { |m| f.call(m) }
end
>> method(:nest).to_proc.curry.call(method(:f), 3).call(1)
=> 8
如果想要看起来更像函数调用的东西,您也可以使用 []
代替 call
:
def nest(f, n, x)
n.times.inject(x) { |m| f[m] }
end
>> method(:nest).to_proc.curry[method(:f), 3][1]
=> 8
关于用于 Mathematica 嵌套函数的 Ruby Eqv?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9425422/