类似于 Haskells 循环的 Ruby 方法

标签 ruby haskell functional-programming

有没有类似于Haskell循环的Ruby方法? Haskell 的循环接受一个列表并返回无限附加到自身的列表。它通常与 take 一起使用,它从数组的顶部抓取一定数量的元素。是否有一个 Ruby 方法接受一个数组并返回附​​加到自身的数组 n 次?

最佳答案

是的,它叫cycle .来自文档:

Array.cycle

(from ruby core)
------------------------------------------------------------------------------
  ary.cycle(n=nil) {|obj| block }  -> nil
  ary.cycle(n=nil)                 -> an_enumerator


------------------------------------------------------------------------------

Calls block for each element repeatedly n times or forever if none
or nil is given.  If a non-positive number is given or the array is empty, does
nothing.  Returns nil if the loop has finished without getting interrupted.

If no block is given, an enumerator is returned instead.

  a = ["a", "b", "c"]
  a.cycle {|x| puts x }  # print, a, b, c, a, b, c,.. forever.
  a.cycle(2) {|x| puts x }  # print, a, b, c, a, b, c.

Edit:

It seems like whats inside the block is basically a "Lambda", and as far as I know, I can't make a lambda concat each element onto an existing array.

b = [1, 2, 3]
z = []
b.cycle(2) { |i| z << i }
z # => [1, 2, 3, 1, 2, 3]

关于类似于 Haskells 循环的 Ruby 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15240840/

相关文章:

python - 是否有用于将列表过滤为真和假的函数式编程习惯用法?

ruby - gem 很慢

Ruby RVM apt-get更新错误

haskell - 函数组合和 $ - 一个编译,另一个不编译

haskell - GHC panic : Loading temp shared object failed

Python:如果某个属性为真,则允许调用某些方法

functional-programming - StandardML 中的 y 组合器

ruby-on-rails - Rails 基本搜索和 PostgreSQL

ruby-on-rails - Rails、Rake、将文件夹移动到新位置

list - 如何使用元组的元素作为索引来访问列表的元素-haskell