在创建单向的、延迟计算的、潜在无限的迭代器方面,我在使用Ruby的初期遇到了一些问题。基本上,我正在尝试使用Ruby,就像使用Haskell列表一样,在较小的程度上,使用Python生成器。
这并不是我不理解它们本身;我只是不知道如何像其他语言那样随意地使用它们,而且我也不确定Ruby中的哪些方法会在我背后将它们转换为数组,从而不必要地将整个序列卸载到内存中。
是的,我一直在研究Ruby参考手册。实际上是半个小时,全神贯注。或者很明显不是。
例如,如果我要实现一个卡片组,它将在Python中如下所示(未经测试):
# Python 3
from itertools import chain, count
face_ranks =
dict(
zip(
('jack', 'queen', 'king', 'ace'),
count(11)))
sorted_deck =
map(
lambda suit:
map(
lambda rank:
{
'rank' : rank,
'suit' : suit
},
chain(
range(2, 11),
face_ranks.keys())),
('clubs', 'diamonds', 'hearts', 'spades'))
那么,我该如何在Ruby中做到这一点,完全避免数组呢?请注意,据我所知,上面的代码只使用元组和生成器:不会像我使用数组那样将整个序列转储到内存中。我可能看错了上面的代码,但是你得到了我想要的。
如何链接迭代器(如Python的chain())?如何生成无限范围的迭代器(如Python的count())?如何将数组添加到迭代器中(就像将元组传递给Python的chain()),而不将整个过程转换为数组?
我见过解决方案,但它们涉及数组或不必要的复杂性,如光纤。
在Python中,我可以像处理数组一样简单地操作和使用迭代器。我几乎可以像对待Haskell列表一样对待它们,这是我最喜欢的,也是我在编码时所考虑的。我对Ruby数组不太满意,这就是为什么我在它的替代方案上寻求帮助。
我已经设法在互联网上找到了关于它的大量信息,但我找不到任何涵盖Ruby中此类数据结构的基本操作的信息?有什么帮助吗?
发布于 2011-08-08 12:18:45
Ruby似乎没有很多内置的方法来做你想用枚举器做的不同的事情,但是你可以创建你自己的方法。这就是我在这里所做的,使用Ruby 1.9:
iter.rb
def get_enums_from_args(args)
args.collect { |e| e.is_a?(Enumerator) ? e.dup : e.to_enum }
end
def build(y, &block)
while true
y << (begin yield; rescue StopIteration; break; end)
end
end
def zip(*args)
enums = get_enums_from_args args
Enumerator.new do |y|
build y do
enums.collect { |e| e.next }
end
end
end
def chain(*args)
enums = get_enums_from_args args
Enumerator.new do |y|
enums.each do |e|
build y do
e.next
end
end
end
end
def multiply(*args)
enums = get_enums_from_args args
duped_enums = enums.collect { |e| e.dup }
Enumerator.new do |y|
begin
while true
y << (begin; enums.collect { |e| e.peek }; rescue StopIteration; break; end )
index = enums.length - 1
while true
begin
enums[index].next
enums[index].peek
break
rescue StopIteration
# Some iterator ran out of items.
# If it was the first iterator, we are done,
raise if index == 0
# If it was a different iterator, reset it
# and then look at the iterator before it.
enums[index] = duped_enums[index].dup
index -= 1
end
end
end
rescue StopIteration
end
end
end
我使用rspec编写了一个规范来测试函数并演示它们的作用:
iter_spec.rb:
require_relative 'iter'
describe "zip" do
it "zips together enumerators" do
e1 = "Louis".chars
e2 = "198".chars
zip(e1,e2).to_a.should == [ ['L','1'], ['o','9'], ['u','8'] ]
end
it "works with arrays too" do
zip([1,2], [:a, nil]).to_a.should == [ [1,:a], [2,nil] ]
end
end
describe "chain" do
it "chains enumerators" do
e1 = "Jon".chars
e2 = 0..99999999999
e = chain(e1, e2)
e.next.should == "J"
e.next.should == "o"
e.next.should == "n"
e.next.should == 0
e.next.should == 1
end
end
describe "multiply" do
it "multiplies enumerators" do
e1 = "ABC".chars
e2 = 1..3
multiply(e1, e2).to_a.should == [["A", 1], ["A", 2], ["A", 3], ["B", 1], ["B", 2], ["B", 3], ["C", 1], ["C", 2], ["C", 3]]
end
it "is lazily evalutated" do
e1 = 0..999999999
e2 = 1..3
e = multiply(e1, e2)
e.next.should == [0, 1]
e.next.should == [0, 2]
e.next.should == [0, 3]
e.next.should == [1, 1]
e.next.should == [1, 2]
end
it "resulting enumerator can not be cloned effectively" do
ranks = chain(2..10, [:jack, :queen, :king, :ace])
suits = [:clubs, :diamonds, :hearts, :spades]
cards = multiply(suits, ranks)
c2 = cards.clone
cards.next.should == [:clubs, 2]
c2.next.should == [:clubs, 2]
c2.next.should == [:clubs, 3]
c2.next.should == [:clubs, 4]
c2.next.should == [:clubs, 5]
cards.next.should == [:clubs, 6]
end
it "resulting enumerator can not be duplicated after first item is evaluated" do
ranks = chain(2..10, [:jack, :queen, :king, :ace])
suits = [:clubs, :diamonds, :hearts, :spades]
cards = multiply(ranks, suits)
cards.peek
lambda { cards.dup }.should raise_error TypeError
end
end
如上面的规范所示,这些方法使用惰性求值。
此外,这里定义的zip
、chain
和multiply
函数的主要缺点是不能容易地复制或克隆结果枚举器,因为我们没有编写任何代码来复制这些新枚举器所依赖的枚举参数。你可能需要创建一个Enumerator
的子类,或者创建一个包含Enumerable
模块的类,或者类似的东西来让dup
很好地工作。
发布于 2011-08-08 10:15:55
您似乎是出于性能焦虑而避免使用Ruby数组,可能是由于您在其他语言中使用过数组的经验。你不必回避Ruby数组,- they是你在Ruby中最接近元组的东西。
foo = 1, 2, 3, 4
foo.class #=> Array
看起来您正在寻找一个范围而不是生成器:
range = 1..4
range.class #=> Range
range.count #=> 4
('a'..'z').each { |letter| letter.do_something }
范围不会转换为数组,但它包含Enumerable,因此您可以使用所有常规枚举器。就循环/迭代而言,- the中的原生循环是通过Enumerable实现的。for i in group
实际上是枚举器循环(如.each
)的语法糖。可枚举的方法通常返回发送者,因此您可以链接它们:
(1..10).map { |n| n * 2 }.each { |n| print "##{n}" }
# outputs #2#4#6#8#10#12#14#16#18#20
# returns an array:
#=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
我很乐意为你的Python»Ruby等价物给出更具体的答案,但我对Python并不熟悉。
更新
您可以将范围压缩到一个嵌套数组中,如下所示:
(1..26).zip('a'..'z') #=> [[1, 'a'], [2, 'b'], ...]
…但是Ranges不是可变的。您可以使用(1..5).to_a
将范围转换为数组,也可以像我上面显示的那样遍历它。如果您有多个定义的数据范围要测试是否包含,您可以使用两个范围和一个映射:
allowed = 'a'..'z', 1..100
input = # whatever
allowed.each do |range|
return false unless range.cover? input
end
当然,您总是可以使用带范围的枚举数来动态“生成”值。
发布于 2011-08-08 10:25:24
Ruby语言中最接近的等价物是Enumerator。它可以让你做懒惰的生成器。
https://stackoverflow.com/questions/6977092
复制相似问题