Module: Kernel

Defined in:
lib/lab42/stream/empty.rb,
lib/lab42/stream/kernel.rb

Overview

class Empty

Instance Method Summary collapse

Instance Method Details

#binop_streams(op, stream1, stream2) ⇒ Object



3
4
5
6
7
# File 'lib/lab42/stream/kernel.rb', line 3

def binop_streams op, stream1, stream2
  combine_streams stream1, stream2 do |e1, e2|
    e1.send op, e2
  end
end

#combine_streams(s1, s2, op = nil, &operation) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/lab42/stream/kernel.rb', line 9

def combine_streams s1, s2, op=nil, &operation
  return empty_stream if s1.empty? || s2.empty?
  op ||= operation
  cons_stream op.(s1.head, s2.head) do
    combine_streams( s1.tail, s2.tail, op)
  end
end

#cons_stream(head, &tail) ⇒ Object



17
18
19
# File 'lib/lab42/stream/kernel.rb', line 17

def cons_stream head, &tail
  Lab42::Stream.new head, tail
end

#const_stream(const) ⇒ Object



21
22
23
# File 'lib/lab42/stream/kernel.rb', line 21

def const_stream const
  c = cons_stream( const ){ c }
end

#cyclic_stream(*args) ⇒ Object



25
26
27
28
29
30
# File 'lib/lab42/stream/kernel.rb', line 25

def cyclic_stream *args
  args = args.first if
    args.size == 1 && Enumerable === args.first

  finite_stream( args ).make_cyclic
end

#empty_streamObject



39
# File 'lib/lab42/stream/empty.rb', line 39

def empty_stream; Empty.new end

#finite_stream(enum) ⇒ Object



32
33
34
35
36
37
# File 'lib/lab42/stream/kernel.rb', line 32

def finite_stream enum
  e = enum.lazy
  cons_stream( e.peek ){ finite_stream e.drop( 1 ) }
rescue StopIteration
  empty_stream
end

#flatmap(stream, *args, &blk) ⇒ Object



39
40
41
# File 'lib/lab42/stream/kernel.rb', line 39

def flatmap stream, *args, &blk
  stream.flatmap( *args, &blk )
end

#merge_streams(*streams) ⇒ Object

TODO: Reimplement with a cursor into streams to avoid the (potentially) costly array arithm in the tail def



45
46
47
48
49
50
51
# File 'lib/lab42/stream/kernel.rb', line 45

def merge_streams *streams
  s = streams.reject( &:empty? )
  return empty_stream if s.empty?
  cons_stream s.first.head do
    merge_streams(*(s.drop(1) + [s.first.tail]))
  end
end

#stream_by(*args, &blk) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/lab42/stream/kernel.rb', line 53

def stream_by *args, &blk
  if blk
    cons_stream(*args){ stream_by( blk.(*args), &blk ) }
  else
    rest = args.drop 1
    if Method === rest.first 
      cons_stream( args.first ){ stream_by( rest.first.(*([args.first] + rest.drop(1))), *rest ) }
    else
      cons_stream( args.first ){ stream_by( sendmsg(*rest).(args.first), *rest ) }
  end
  end
end