Class: Seq::Lazy

Inherits:
Seq
  • Object
show all
Defined in:
lib/seq/lazy.rb

Overview

Lazy seqs evaluate a block to determine the next value when needed, this value is then saved.

Examples:


s = Seq::Lazy.new([1]) { 1 }
s.take(3) #=> [1, 1, 1]

ns = Seq::Lazy.new([1]) {|l| l[-1] + 1 }
ns.take(5) #=> [1, 2, 3, 4, 5]

fibs = Seq::Lazy.new([1, 1]) {|l| l[-1] + l[-2] }
fibs.take(7) #=> [1, 1, 2, 3, 5, 8, 13]
fibs.take!(7) #=> [21, 34, 55, 89, 144, 233, 377]
fibs.take!(2) #=> [21, 34]

Constant Summary

Constants inherited from Seq

VERSION

Instance Method Summary collapse

Methods inherited from Seq

#each, #ended?, #entries, #inc, #infinite?, #method_missing, #to_a

Constructor Details

#initialize(list = [], items = Float::INFINITY, offset = 0, default = nil) {|list| ... } ⇒ Lazy

Creates a new Lazy seq instance.

Parameters:

  • list (Array) (defaults to: [])

    Starting values

  • items (Integer) (defaults to: Float::INFINITY)

    Number of values to return

  • offset (Integer) (defaults to: 0)

    Index of item to start at

  • default (Object) (defaults to: nil)

    Value to return when finished cycling

Yields:

  • (list)

    Block to be called which returns the next value in the list

Yield Parameters:

  • list (Array)

    The list calculated up to the current point



32
33
34
35
36
37
38
39
40
# File 'lib/seq/lazy.rb', line 32

def initialize(list=[], items=Float::INFINITY, offset=0, default=nil, &block)
  @list    = list
  @items   = items
  @block   = block
  @offset  = offset
  @default = default

  self.reset
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Seq

Instance Method Details

#nextObject

Returns Until ended it returns the next item from list if it exists or calculates it then stores it in list, if ended it returns the default value.

Returns:

  • (Object)

    Until ended it returns the next item from list if it exists or calculates it then stores it in list, if ended it returns the default value.



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/seq/lazy.rb', line 59

def next
  if ended?
    @default
  else
    @index += 1
    if @index-1 < @list.size
      @list[@index-1]
    else
      @list[@index-1] = @block.call(@list)
    end
  end
end

#resetObject

Resets the state of the lazy seq. It also calculates any values necessary to get to the offset.



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/seq/lazy.rb', line 44

def reset
  @index  = @list.size
  @cycles = 0

  until @list.size >= @offset
    @list[@index] = @block.call(@list[0..@index-1])
    @index += 1
  end

  @index = @offset
end