Module: Immutable::Consable::ClassMethods

Defined in:
lib/immutable/consable.rb

Instance Method Summary collapse

Instance Method Details

#[](*elements) ⇒ Consable

Creates a new Consable object populated with the given objects.

Parameters:

  • elements (Array<Object>)

    the elements of the Consable object.

Returns:

  • (Consable)

    the new Consable object.



13
14
15
# File 'lib/immutable/consable.rb', line 13

def [](*elements)
  from_array(elements)
end

#from_array(ary) ⇒ Consable

Converts the given array to a Consable object.

Parameters:

  • ary (Array, #reverse_each)

    the array to convert.

Returns:

  • (Consable)

    the Consable object converted from ary.



21
22
23
24
25
# File 'lib/immutable/consable.rb', line 21

def from_array(ary)
  ary.reverse_each.inject(empty) { |x, y|
    Cons(y, x)
  }
end

#from_enum(enum) ⇒ Cons

Converts the given Enumerable object to a Consable object.

Parameters:

  • enum (#inject)

    the Enumerable object to convert.

Returns:

  • (Cons)

    the Consable object converted from enum.



31
32
33
34
35
# File 'lib/immutable/consable.rb', line 31

def from_enum(enum)
  enum.inject(empty) { |x, y|
    Cons(y, x)
  }.reverse
end

#unfoldr(e, &block) ⇒ Consable

Builds a Consable object from the seed value e and the given block. The block takes a seed value and returns nil if the seed should unfold to the empty Consable object, or returns [a, b], where a is the head of the Consable object and b is the next seed from which to unfold the tail. For example:

xs = List.unfoldr(3) { |x| x == 0 ? nil : [x, x - 1] }
p xs #=> List[3, 2, 1]

unfoldr is the dual of foldr.

and the block.

Parameters:

  • e (Object)

    the seed value.

Returns:

  • (Consable)

    the Consable object built from the seed value



51
52
53
54
55
56
57
58
59
# File 'lib/immutable/consable.rb', line 51

def unfoldr(e, &block)
  x = yield(e)
  if x.nil?
    empty
  else
    y, z = x
    Cons(y, unfoldr(z, &block))
  end
end