Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Enumerating lazily
Index -> Programming, Ruby -> Ruby Submissions
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: 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
}
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: 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
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Submissions
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: