ruby - 与 Haskell 的 scanl 对应的 Ruby 是什么?

标签 ruby

This question在 Python 中展示了 Haskell 的 scanl 版本,但是这个函数有 Ruby 版本吗?

最佳答案

可以使用reduce(),自己实现。

def scanl(op, init, range)
  op = op.to_proc unless op.is_a?(Proc)
  range.reduce([init]) { |a, e| a.push(op.call(a.last,e)) }
end

p scanl(lambda { |a, b| a + b }, 0, 1..10)
#=> [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
p scanl(:+, 0, 1..10)
#=> [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

或者,您可以使用 map() 并将初始元素放在数组前面。

def scanl(op, init, range)                             
  op = op.to_proc unless op.is_a?(Proc)                
  acc = init                                           
  range.map { |e| acc = op.call(acc, e) }.unshift(init)
end                                                 

关于ruby - 与 Haskell 的 scanl 对应的 Ruby 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38104139/

相关文章:

ruby-on-rails - Rails 渲染 ajax 错误

ruby - 什么是 'rvm_codesign_identity' 以及如何设置它?

ruby - 以编程方式编辑 crontab 并强制守护进程刷新

Ruby - Feedzirra 和更新

ruby - 在ruby中卸载动态声明的类

ruby-on-rails - 如何找到 24 个月内每月的捐款总额?

ruby-on-rails - 很抱歉,当用户尝试注册时,heroku 出现了问题

ruby - (跨平台)检查文件路径是否绝对,而不使用 Pathname 库

ruby - 返回可以为多个的所有最大值或最小值

ruby-on-rails - RSpec 和 rails : Stub @virtual_path for translation helper to test an application helper