用于 Mathematica 嵌套函数的 Ruby Eqv?

标签 ruby nested

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/

相关文章:

python - 我们可以在 tkinter 中嵌套两个 OptionMenu 小部件吗?

ruby - Github Actions 无法在 ubuntu-18.04.5 上安装 Libv8 gem

javascript - 是什么阻止了 Ryan Dahl(Node 的创建者)在 Ruby 而不是 Javascript 中创建与 Node 相同的概念

c++ - c 中的嵌套 union

MySQL 嵌套选择查询性能

haskell - Haskell 中的嵌套列表理解

json - Marvel API Swift4 JSON 解码

ruby-on-rails - 如何在 Postgres 数据库中存储正则表达式或搜索词并在 Rails Query 中进行评估?

ruby-on-rails - AWS S3 Ruby url_for 响应 header (自定义文件名和文件类型)

ruby-on-rails - 如何更新 RoR 模型的关联而不更新相应模型的属性