Module: LazyList::ObjectMethods

Included in:
Object
Defined in:
lib/lazylist.rb

Overview

This module contains methods that are included into Ruby’s Kernel module.

Instance Method Summary collapse

Instance Method Details

#build(&block) ⇒ Object

This method returns a Lazylist::ListBuilder instance for tuplewise building of lists like the zip method does. This method call

build { x + y }.where(:x => 1..3, :y => 1..3)

returns the same list [ 2, 4, 6 ] as this expression does

LazyList[1..3].zip(LazyList[1..3]) { |x, y| x + y }


817
818
819
# File 'lib/lazylist.rb', line 817

def build(&block)
  LazyList::ListBuilder.create_build(&block)
end

#list(*values, &block) ⇒ Object

A method to improve the user friendliness for creating new lazy lists, that cannot be described well with LazyList.iterate or LazyList.tabulate.

  • list without any arguments, returns the empty lazy list LazyList::Empty.

  • list { x / y } returns a LazyList::ListBuilder object for a list comprehension, that can be transformed into a LazyList by calling the LazyList::ListBuilder#where method.

  • list(x) returns the lazy list with only the element x as a member, list(x,y) returns the lazy list with only the elements x and y as a members, and so on.

  • list(x) { xs } returns the lazy list with the element x as a head element, and that is continued with the lazy list xs as tail. To define an infinite lazy list of 1s you can do:

    ones = list(1) { ones } # => [1,... ]
    

    To define all even numbers directly, you can do:

    def even(n = 0) list(n) { even(n + 2) } end
    

    and then:

    e = even # => [0,... ]
    


794
795
796
797
798
799
800
801
802
803
804
805
806
807
# File 'lib/lazylist.rb', line 794

def list(*values, &block)
  values_empty = values.empty?
  result = LazyList[values]
  if block_given?
    if values_empty
      result = LazyList::ListBuilder.create_comprehend(&block)
    else
      result.instance_eval do
        ref(values.size - 1)
      end.instance_variable_set(:@tail, LazyList.delay(&block))
    end
  end
  result
end