Created
November 13, 2008 17:14
-
-
Save practicingruby/24506 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require "enumerator" | |
| module LazyStream | |
| class Node | |
| def initialize( head, &promise ) | |
| @head, @tail = head, promise | |
| end | |
| attr_reader :head | |
| alias_method :current, :head | |
| def tail | |
| if @tail.is_a? Proc | |
| @tail.call | |
| else | |
| @tail | |
| end | |
| end | |
| alias_method :next, :tail | |
| def drop | |
| result, next_stream = head, tail | |
| @head, @tail = if next_stream.is_a? self.class | |
| next_stream.instance_eval { [@head, @tail] } | |
| else | |
| Array(next_stream) | |
| end | |
| result | |
| end | |
| alias_method :tail!, :drop | |
| alias_method :next!, :drop | |
| def end? | |
| @tail.nil? | |
| end | |
| def next? | |
| not end? | |
| end | |
| def show( *limit_and_options ) | |
| options = {:sep => " ", :end => "\n"}.merge!( | |
| limit_and_options.last.is_a?(Hash) ? limit_and_options.pop : Hash.new | |
| ) | |
| limit = limit_and_options.shift | |
| each(limit) { |cur| print cur, options[:sep] } | |
| print options[:end] | |
| end | |
| alias_method :display, :show | |
| def each!( limit = nil ) | |
| loop do | |
| break unless limit.nil? or (limit -= 1) > -1 | |
| yield drop | |
| break if end? | |
| end | |
| self | |
| end | |
| def each( limit = nil, &block ) | |
| clone.each!(limit, &block) | |
| self | |
| end | |
| alias_method :peek, :each | |
| include Enumerable | |
| def limit( max_depth = nil ) | |
| enum_for(:each, max_depth) | |
| end | |
| def limit!( max_depth = nil ) | |
| enum_for(:each!, max_depth) | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment