Ruby的Eqv用于Mathematica的Nest函数?

时间:2012-02-24 04:30:59

标签: ruby nested

Here's Mathematica's Nest function Definition。什么是eqv。在Ruby?

这个想法是这样的:

nest(f, x, 3) #=> f(f(f(x)))

2 个答案:

答案 0 :(得分:2)

您可以使用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

答案 1 :(得分:1)

我不认识Ruby,但我查看了该语言的描述并编写了以下代码..

让它成为你的功能

def func(­x)  
   return sin(x­)
end

并定义一个嵌套函数

def nest(­f, x, n)
    count = 0
    while count­<n
        x = send(f, x)
        count += 1
    end
    return x
end

将其称为nest(:func­, 1, 3),结果将为0.67843047736074

我将它与http://www.wolframalpha.com上的结果进行了比较,得到了相同的答案。