Jos*_*sto 2 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.
编辑:
看起来块中的内容基本上是"Lambda",据我所知,我不能将lambda concat每个元素连接到现有数组上.
b = [1, 2, 3]
z = []
b.cycle(2) { |i| z << i }
z # => [1, 2, 3, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
161 次 |
| 最近记录: |