Module: Enumerators
- Defined in:
- lib/enumerators.rb
Instance Method Summary collapse
- #character_enumerator(string) ⇒ Object
- #empty_enumerator ⇒ Object
- #enumerator(fn, init) ⇒ Object
- #flatten_enumerator(enumerator) ⇒ Object
- #has_next(e) ⇒ Object
- #repeat_enumerator(value) ⇒ Object
- #repeat_fn_enumerator(fn) ⇒ Object
- #reverse(e) ⇒ Object
Instance Method Details
#character_enumerator(string) ⇒ Object
38 39 40 41 42 43 44 45 46 47 |
# File 'lib/enumerators.rb', line 38 def character_enumerator(string) Enumerator.new do |y| index = 0 loop do raise StopIteration.new unless index < string.size y << string[index] index = index + 1 end end.lazy end |
#empty_enumerator ⇒ Object
71 72 73 |
# File 'lib/enumerators.rb', line 71 def empty_enumerator [].lazy end |
#enumerator(fn, init) ⇒ Object
15 16 17 18 19 20 21 22 23 24 |
# File 'lib/enumerators.rb', line 15 def enumerator(fn, init) Enumerator.new do |y| value = init y << value loop do value = fn.(value) y << value end end.lazy end |
#flatten_enumerator(enumerator) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/enumerators.rb', line 49 def flatten_enumerator(enumerator) Enumerator.new do |y| current_enumerator = empty_enumerator loop do until has_next(current_enumerator) unless has_next(enumerator) current_enumerator = empty_enumerator break end current_enumerator = enumerator.next.enumerator end if has_next(current_enumerator) y << current_enumerator.next else raise StopIteration.new end end end.lazy end |
#has_next(e) ⇒ Object
6 7 8 9 10 11 12 13 |
# File 'lib/enumerators.rb', line 6 def has_next(e) begin e.peek true rescue StopIteration false end end |
#repeat_enumerator(value) ⇒ Object
26 27 28 |
# File 'lib/enumerators.rb', line 26 def repeat_enumerator(value) Enumerators.repeat_fn_enumerator(returns(value)) end |
#repeat_fn_enumerator(fn) ⇒ Object
30 31 32 33 34 35 36 |
# File 'lib/enumerators.rb', line 30 def repeat_fn_enumerator(fn) Enumerator.new do |y| loop do y << fn.() end end.lazy end |
#reverse(e) ⇒ Object
2 3 4 |
# File 'lib/enumerators.rb', line 2 def reverse(e) e.reverse_each end |