Module: Immutable::Consable::ClassMethods
- Defined in:
- lib/immutable/consable.rb
Instance Method Summary collapse
-
#[](*elements) ⇒ Consable
Creates a new
Consable
object populated with the given objects. -
#from_array(ary) ⇒ Consable
Converts the given array to a
Consable
object. -
#from_enum(enum) ⇒ Cons
Converts the given Enumerable object to a
Consable
object. -
#unfoldr(e, &block) ⇒ Consable
Builds a
Consable
object from the seed valuee
and the given block.
Instance Method Details
#[](*elements) ⇒ Consable
Creates a new Consable
object populated with the given objects.
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.
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.
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.
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 |