class X
def initialize(obj)
@obj = obj
@calls = [] end
def collect(&block)
@calls.push([:collect, block]) self end
defeach(&block)
@calls.push([:each, block])
@obj.eachdo |x|
@calls.eachdo |c|
r = c[1].call(x)
x = r if c[0] == :collect
end end
@calls = [] end
end
module Enumerable
def lazy
X.new(self) end
end
[1, 2, 3].lazy.collect{ |x|
x * 2 }.collect{ |x|
x + 1 }.each{ |x|
puts x
breakif x > 4 }
Author:
wtd [ Mon Feb 01, 2010 12:31 am ]
Post subject:
Re: Enumerating lazily
code:
>> [1, 2, 3].lazy.collect { |x|
?> puts "loop one #{x}"
>> x * 2
>> }.collect { |x|
?> puts "loop two #{x}"
>> x + 1
>> }.each { |x|
?> puts x
>> break if x > 4
>> }
loop one 1
loop two 2
3
loop one 2
loop two 4
5
=> nil
code:
>> [1, 2, 3].collect { |x|
?> puts "loop one #{x}"
>> x * 2
>> }.collect { |x|
?> puts "loop two #{x}"
>> x + 1
>> }.each { |x|
?> puts x
>> break if x > 4
>> }
loop one 1
loop one 2
loop one 3
loop two 2
loop two 4
loop two 6
3
5
=> nil