Enumerating lazily
Author |
Message |
wtd
|
Posted: Sun Jan 31, 2010 11:47 pm Post subject: Enumerating lazily |
|
|
Ruby: | class X
def initialize(obj)
@obj = obj
@calls = []
end
def collect(&block)
@calls.push([:collect, block])
self
end
def each(&block)
@calls.push([:each, block])
@obj.each do |x|
@calls.each do |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
break if x > 4
} |
|
|
|
|
|
![](images/spacer.gif) |
Sponsor Sponsor
![Sponsor Sponsor](templates/subSilver/images/ranks/stars_rank5.gif)
|
|
![](images/spacer.gif) |
wtd
|
Posted: 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 |
|
|
|
|
|
![](images/spacer.gif) |
|
|