Method: Immutable::Stream.unfoldr

Defined in:
lib/immutable/stream.rb

.unfoldr(e, &block) ⇒ Stream

Builds a stream 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 stream, or returns [a, b], where a is the head of the stream 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.

Parameters:

  • e (Object)

    the seed value.

Returns:

  • (Stream)

    the stream built from the seed value and the block.



404
405
406
407
408
409
410
411
412
413
414
# File 'lib/immutable/stream.rb', line 404

def self.unfoldr(e, &block)
  Stream.lazy {
    x = yield(e)
    if x.nil?
      Stream.empty
    else
      y, z = x
      Stream.cons ->{ y }, ->{ unfoldr(z, &block) }
    end
  }
end