-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathiterator.cr
1887 lines (1666 loc) · 47.8 KB
/
iterator.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require "./enumerable"
# An `Iterator` allows processing sequences lazily, as opposed to `Enumerable` which processes
# sequences eagerly and produces an `Array` in most of its methods.
#
# As an example, let's compute the first three numbers in the range `1..10_000_000` that are even,
# multiplied by three. One way to do this is:
#
# ```
# (1..10_000_000).select(&.even?).map { |x| x * 3 }.first(3) # => [6, 12, 18]
# ```
#
# The above works, but creates many intermediate arrays: one for the `select` call,
# one for the `map` call and one for the `first` call. A more efficient way is to invoke
# `Range#each` without a block, which gives us an `Iterator` so we can process the operations
# lazily:
#
# ```
# (1..10_000_000).each.select(&.even?).map { |x| x * 3 }.first(3) # => #< Iterator(T)::First...
# ```
#
# `Iterator` redefines many of `Enumerable`'s method in a lazy way, returning iterators
# instead of arrays.
#
# At the end of the call chain we get back a new iterator: we need to consume it, either
# using `each` or `Enumerable#to_a`:
#
# ```
# (1..10_000_000).each.select(&.even?).map { |x| x * 3 }.first(3).to_a # => [6, 12, 18]
# ```
#
# Because iterators only go forward, when using methods that consume it entirely or partially –
# `to_a`, `any?`, `count`, `none?`, `one?` and `size` – subsequent calls will give a different
# result as there will be less elements to consume.
#
# ```
# iter = (0...100).each
# iter.size # => 100
# iter.size # => 0
# ```
#
# ### Iterating step-by-step
#
# An iterator returns its next element on the method `#next`.
# Its return type is a union of the iterator's element type and the `Stop` type:
# `T | Iterator::Stop`.
# The stop type is a sentinel value which indicates that the iterator has
# reached its end. It usually needs to be handled and filtered out in order to
# use the element value for anything useful.
# Unlike `Nil` it's not an implicitly falsey type.
#
# ```
# iter = (1..5).each
#
# # Unfiltered elements contain `Iterator::Stop` type
# iter.next + iter.next # Error: expected argument #1 to 'Int32#+' to be Int32, not (Int32 | Iterator::Stop)
#
# # Type filtering eliminates the stop type
# a = iter.next
# b = iter.next
# unless a.is_a?(Iterator::Stop) || b.is_a?(Iterator::Stop)
# a + b # => 3
# end
# ```
#
# `Iterator::Stop` is only present in the return type of `#next`. All other
# methods remove it from their return types.
#
# Iterators can be used to build a loop.
#
# ```
# iter = (1..5).each
# sum = 0
# while !(elem = iter.next).is_a?(Iterator::Stop)
# sum += elem
# end
# sum # => 15
# ```
#
# ### Implementing an Iterator
#
# To implement an `Iterator` you need to define a `next` method that must return the next
# element in the sequence or `Iterator::Stop::INSTANCE`, which signals the end of the sequence
# (you can invoke `stop` inside an iterator as a shortcut).
#
# For example, this is an iterator that returns a sequence of `N` zeros:
#
# ```
# class Zeros
# include Iterator(Int32)
#
# def initialize(@size : Int32)
# @produced = 0
# end
#
# def next
# if @produced < @size
# @produced += 1
# 0
# else
# stop
# end
# end
# end
#
# zeros = Zeros.new(5)
# zeros.to_a # => [0, 0, 0, 0, 0]
# ```
#
# The standard library provides iterators for many classes, like `Array`, `Hash`, `Range`, `String` and `IO`.
# Usually to get an iterator you invoke a method that would usually yield elements to a block,
# but without passing a block: `Array#each`, `Array#each_index`, `Hash#each`, `String#each_char`,
# `IO#each_line`, etc.
module Iterator(T)
include Enumerable(T)
# The class that signals that there are no more elements in an `Iterator`.
class Stop
INSTANCE = new
end
# `IteratorWrapper` eliminates some boilerplate when defining
# an `Iterator` that wraps another iterator.
#
# To use it, include this module in your iterator and make sure that the wrapped
# iterator is stored in the `@iterator` instance variable.
module IteratorWrapper
# Invokes `next` on the wrapped iterator and returns `stop` if
# the given value was a `Iterator::Stop`. Otherwise, returns the value.
macro wrapped_next
%value = @iterator.next
return stop if %value.is_a?(Stop)
%value
end
end
# Shortcut for `Iterator::Stop::INSTANCE`, to signal that there are no more elements in an iterator.
def stop
Iterator.stop
end
# :ditto:
def self.stop
Stop::INSTANCE
end
# Returns an empty iterator.
def self.empty
EmptyIterator(T).new
end
private struct EmptyIterator(T)
include Iterator(T)
def next
stop
end
end
def self.of(element : T)
SingletonIterator(T).new(element)
end
private struct SingletonIterator(T)
include Iterator(T)
def initialize(@element : T)
end
def next
@element
end
end
def self.of(&block : -> T)
SingletonProcIterator(typeof(without_stop(&block))).new(block)
end
private def self.without_stop(&block : -> T)
e = block.call
raise "" if e.is_a?(Iterator::Stop)
e
end
private struct SingletonProcIterator(T)
include Iterator(T)
def initialize(@proc : (-> (T | Iterator::Stop)) | (-> T))
end
def next
@proc.call
end
end
# Returns the next element in this iterator, or `Iterator::Stop::INSTANCE` if there
# are no more elements.
abstract def next
# Returns an iterator that returns the prefix sums of the original iterator's
# elements.
#
# Expects `T` to respond to the `#+` method.
#
# ```
# iter = (3..6).each.accumulate
# iter.next # => 3
# iter.next # => 7
# iter.next # => 12
# iter.next # => 18
# iter.next # => Iterator::Stop::INSTANCE
# ```
def accumulate
accumulate { |x, y| x + y }
end
# Returns an iterator that returns *initial* and its prefix sums with the
# original iterator's elements.
#
# Expects `U` to respond to the `#+` method.
#
# ```
# iter = (3..6).each.accumulate(7)
# iter.next # => 7
# iter.next # => 10
# iter.next # => 14
# iter.next # => 19
# iter.next # => 25
# iter.next # => Iterator::Stop::INSTANCE
# ```
def accumulate(initial : U) forall U
accumulate(initial) { |x, y| x + y }
end
# Returns an iterator that accumulates the original iterator's elements by
# the given *block*.
#
# For each element of the original iterator the block is passed an accumulator
# value and the element. The result becomes the new value for the accumulator
# and is then returned. The initial value for the accumulator is the first
# element of the original iterator.
#
# ```
# iter = %w(the quick brown fox).each.accumulate { |x, y| "#{x}, #{y}" }
# iter.next # => "the"
# iter.next # => "the, quick"
# iter.next # => "the, quick, brown"
# iter.next # => "the, quick, brown, fox"
# iter.next # => Iterator::Stop::INSTANCE
# ```
def accumulate(&block : T, T -> T)
AccumulateIterator(typeof(self), T).new(self, block)
end
# Returns an iterator that accumulates *initial* with the original iterator's
# elements by the given *block*.
#
# Similar to `#accumulate(&block : T, T -> T)`, except the initial value is
# provided by an argument and needs not have the same type as the elements of
# the original iterator. This initial value is returned first.
#
# ```
# iter = [4, 3, 2].each.accumulate("X") { |x, y| x * y }
# iter.next # => "X"
# iter.next # => "XXXX"
# iter.next # => "XXXXXXXXXXXX"
# iter.next # => "XXXXXXXXXXXXXXXXXXXXXXXX"
# iter.next # => Iterator::Stop::INSTANCE
# ```
def accumulate(initial : U, &block : U, T -> U) forall U
AccumulateInitIterator(typeof(self), T, U).new(self, initial, block)
end
private class AccumulateInitIterator(I, T, U)
include Iterator(U)
@acc : U | Iterator::Stop
def initialize(@iterator : I, @acc : U, @func : U, T -> U)
end
def next
old_acc = @acc
return old_acc if old_acc.is_a?(Iterator::Stop)
elem = @iterator.next
@acc = elem.is_a?(Iterator::Stop) ? elem : @func.call(old_acc, elem)
old_acc
end
end
private class AccumulateIterator(I, T)
include Iterator(T)
include IteratorWrapper
@acc : T | Iterator::Stop = Iterator::Stop::INSTANCE
def initialize(@iterator : I, @func : T, T -> T)
end
def next
elem = wrapped_next
old_acc = @acc
@acc = old_acc.is_a?(Iterator::Stop) ? elem : @func.call(old_acc, elem)
end
end
# Returns an iterator that returns elements from the original iterator until
# it is exhausted and then returns the elements of the second iterator.
# Compared to `.chain(Iterator(Iter))`, it has better performance when the quantity of
# iterators to chain is small (usually less than 4).
# This method also cannot chain iterators in a loop, for that see `.chain(Iterator(Iter))`.
#
# ```
# iter = (1..2).each.chain(('a'..'b').each)
# iter.next # => 1
# iter.next # => 2
# iter.next # => 'a'
# iter.next # => 'b'
# iter.next # => Iterator::Stop::INSTANCE
# ```
def chain(other : Iterator(U)) forall U
ChainIterator(typeof(self), typeof(other), T, U).new(self, other)
end
private class ChainIterator(I1, I2, T1, T2)
include Iterator(T1 | T2)
def initialize(@iterator1 : I1, @iterator2 : I2)
@iterator1_consumed = false
end
def next
unless @iterator1_consumed
value = @iterator1.next
if value.is_a?(Stop)
@iterator1_consumed = true
else
return value
end
end
@iterator2.next
end
end
# The same as `#chain`, but have better performance when the quantity of
# iterators to chain is large (usually greater than 4) or undetermined.
#
# ```
# array_of_iters = [[1], [2, 3], [4, 5, 6]].each.map &.each
# iter = Iterator(Int32).chain array_of_iters
# iter.next # => 1
# iter.next # => 2
# iter.next # => 3
# iter.next # => 4
# ```
def self.chain(iters : Iterator(Iter)) forall Iter
ChainsAllIterator(Iter, typeof(iters.first.first)).new iters
end
# the same as `.chain(Iterator(Iter))`
def self.chain(iters : Iterable(Iter)) forall Iter
chain iters.each
end
private class ChainsAllIterator(Iter, T)
include Iterator(T)
@iterators : Iterator(Iter)
@current : Iter | Stop
def initialize(@iterators)
@current = @iterators.next
end
def next : T | Stop
return Stop::INSTANCE if (c = @current).is_a? Stop
ret = c.next
while ret.is_a? Stop
c = @current = @iterators.next
return Stop::INSTANCE if c.is_a? Stop
ret = c.next
end
ret
end
end
# Returns an iterator that applies the given function to the element and then
# returns it unless it is `nil`. If the returned value would be `nil` it instead
# returns the next non `nil` value.
#
# ```
# iter = [1, nil, 2, nil].each.compact_map { |e| e.try &.*(2) }
# iter.next # => 2
# iter.next # => 4
# iter.next # => Iterator::Stop::INSTANCE
# ```
def compact_map(&func : T -> _)
CompactMapIterator(typeof(self), T, typeof(func.call(first).not_nil!)).new(self, func)
end
private struct CompactMapIterator(I, T, U)
include Iterator(U)
include IteratorWrapper
def initialize(@iterator : I, @func : T -> U?)
end
def next
while true
value = wrapped_next
mapped_value = @func.call(value)
return mapped_value unless mapped_value.nil?
end
end
end
# Returns an iterator that returns consecutive chunks of the size *n*.
#
# ```
# iter = (1..5).each.cons(3)
# iter.next # => [1, 2, 3]
# iter.next # => [2, 3, 4]
# iter.next # => [3, 4, 5]
# iter.next # => Iterator::Stop::INSTANCE
# ```
#
# By default, a new array is created and returned for each consecutive call of `next`.
# * If *reuse* is given, the array can be reused
# * If *reuse* is `true`, the method will create a new array and reuse it.
# * If *reuse* is an instance of `Array`, `Deque` or a similar collection type (implementing `#<<`, `#shift` and `#size`) it will be used.
# * If *reuse* is falsey, the array will not be reused.
#
# This can be used to prevent many memory allocations when each slice of
# interest is to be used in a read-only fashion.
#
# Chunks of two items can be iterated using `#cons_pair`, an optimized
# implementation for the special case of `n == 2` which avoids heap
# allocations.
def cons(n : Int, reuse = false)
raise ArgumentError.new "Invalid cons size: #{n}" if n <= 0
if reuse.nil? || reuse.is_a?(Bool)
# we use an initial capacity of n * 2, because a second iteration would
# have reallocated the array to that capacity anyway
ConsIterator(typeof(self), T, typeof(n), Array(T)).new(self, n, Array(T).new(n * 2), reuse)
else
ConsIterator(typeof(self), T, typeof(n), typeof(reuse)).new(self, n, reuse, reuse)
end
end
private struct ConsIterator(I, T, N, V)
include Iterator(Array(T))
include IteratorWrapper
def initialize(@iterator : I, @n : N, values : V, reuse)
@values = values
@reuse = !!reuse
end
def next
loop do
elem = wrapped_next
@values << elem
@values.shift if @values.size > @n
break if @values.size == @n
end
if @reuse
@values
else
@values.dup
end
end
end
# Returns an iterator that returns consecutive pairs of adjacent items.
#
# ```
# iter = (1..5).each.cons_pair
# iter.next # => {1, 2}
# iter.next # => {2, 3}
# iter.next # => {3, 4}
# iter.next # => {4, 5}
# iter.next # => Iterator::Stop::INSTANCE
# ```
#
# Chunks of more than two items can be iterated using `#cons`.
# This method is just an optimized implementation for the special case of
# `n == 2` to avoid heap allocations.
def cons_pair : Iterator({T, T})
ConsTupleIterator(typeof(self), T).new(self)
end
private struct ConsTupleIterator(I, T)
include Iterator({T, T})
include IteratorWrapper
@last_elem : T | Iterator::Stop = Iterator::Stop::INSTANCE
def initialize(@iterator : I)
end
def next : {T, T} | Iterator::Stop
elem = wrapped_next
last_elem = @last_elem
if last_elem.is_a?(Iterator::Stop)
@last_elem = elem
self.next
else
value = {last_elem, elem}
@last_elem = elem
value
end
end
end
# Returns an iterator that repeatedly returns the elements of the original
# iterator forever starting back at the beginning when the end was reached.
#
# ```
# iter = ["a", "b", "c"].each.cycle
# iter.next # => "a"
# iter.next # => "b"
# iter.next # => "c"
# iter.next # => "a"
# iter.next # => "b"
# iter.next # => "c"
# iter.next # => "a"
# # and so an and so on
# ```
def cycle
CycleIterator(typeof(self), T).new(self)
end
private struct CycleIterator(I, T)
include Iterator(T)
include IteratorWrapper
def initialize(@iterator : I)
@values = [] of T
@use_values = false
@index = 0
end
def next
if @use_values
return stop if @values.empty?
if @index >= @values.size
@index = 1
return @values.first
end
@index += 1
return @values[@index - 1]
end
value = @iterator.next
if value.is_a?(Stop)
@use_values = true
return stop if @values.empty?
@index = 1
return @values.first
end
@values << value
value
end
end
# Returns an iterator that repeatedly returns the elements of the original
# iterator starting back at the beginning when the end was reached,
# but only *n* times.
#
# ```
# iter = ["a", "b", "c"].each.cycle(2)
# iter.next # => "a"
# iter.next # => "b"
# iter.next # => "c"
# iter.next # => "a"
# iter.next # => "b"
# iter.next # => "c"
# iter.next # => Iterator::Stop::INSTANCE
# ```
def cycle(n : Int)
CycleNIterator(typeof(self), T, typeof(n)).new(self, n)
end
private class CycleNIterator(I, T, N)
include Iterator(T)
include IteratorWrapper
def initialize(@iterator : I, @n : N)
@count = 0
@values = [] of T
@use_values = false
@index = 0
end
def next
return stop if @count >= @n
if @count > 0
return stop if @values.empty?
if @index >= @values.size
@count += 1
return stop if @count >= @n
@index = 1
return @values.first
end
@index += 1
return @values[@index - 1]
end
value = @iterator.next
if value.is_a?(Stop)
@count += 1
return stop if @count >= @n
return stop if @values.empty?
@index = 1
return @values.first
end
@values << value
value
end
end
def each
self
end
# Calls the given block once for each element, passing that element
# as a parameter.
#
# ```
# iter = ["a", "b", "c"].each
# iter.each { |x| print x, " " } # Prints "a b c"
# ```
def each(& : T ->) : Nil
while true
value = self.next
break if value.is_a?(Stop)
yield value
end
end
# Returns an iterator that then returns slices of *n* elements of the initial
# iterator.
#
# ```
# iter = (1..9).each.each_slice(3)
# iter.next # => [1, 2, 3]
# iter.next # => [4, 5, 6]
# iter.next # => [7, 8, 9]
# iter.next # => Iterator::Stop::INSTANCE
# ```
#
# By default, a new array is created and yielded for each consecutive when invoking `next`.
# * If *reuse* is given, the array can be reused
# * If *reuse* is an `Array`, this array will be reused
# * If *reuse* is truthy, the method will create a new array and reuse it.
#
# This can be used to prevent many memory allocations when each slice of
# interest is to be used in a read-only fashion.
def each_slice(n, reuse = false)
slice(n, reuse)
end
# Returns an iterator that flattens nested iterators and arrays into a single iterator
# whose type is the union of the simple types of all of the nested iterators and arrays
# (and their nested iterators and arrays, and so on).
#
# ```
# iter = [(1..2).each, ('a'..'b').each].each.flatten
# iter.next # => 1
# iter.next # => 2
# iter.next # => 'a'
# iter.next # => 'b'
# iter.next # => Iterator::Stop::INSTANCE
# ```
def flatten
FlattenIterator(typeof(FlattenIterator.iterator_type(self)), typeof(FlattenIterator.element_type(self))).new(self)
end
private struct FlattenIterator(I, T)
include Iterator(T)
@iterator : I
@stopped : Array(I)
@generators : Array(I)
def initialize(@iterator)
@generators = [] of I
@stopped = [] of I
end
def next
case value = @iterator.next
when Iterator
@generators.push @iterator
@iterator = value
self.next
when Array
@generators.push @iterator
@iterator = value.each
self.next
when Stop
@stopped << @iterator
if @generators.empty?
stop
else
@iterator = @generators.pop
self.next
end
else
value
end
end
def self.element_type(element)
case element
when Stop
raise ""
when Iterator
element_type(element.next)
when Array
element_type(element.each)
else
element
end
end
def self.iterator_type(iter)
case iter
when Iterator
iter || iterator_type iter.next
when Array
iterator_type iter.each
else
raise ""
end
end
end
# Returns a new iterator with the concatenated results of running the block
# once for every element in the collection.
# Only `Array` and `Iterator` results are concatenated; every other value is
# returned once in the new iterator.
#
# ```
# iter = [1, 2, 3].each.flat_map { |x| [x, x] }
#
# iter.next # => 1
# iter.next # => 1
# iter.next # => 2
#
# iter = [1, 2, 3].each.flat_map { |x| [x, x].each }
#
# iter.to_a # => [1, 1, 2, 2, 3, 3]
# ```
def flat_map(&func : T -> _)
FlatMapIterator(typeof(self), typeof(FlatMapIterator.element_type(self, func)), typeof(FlatMapIterator.iterator_type(self, func)), typeof(func)).new self, func
end
private class FlatMapIterator(I0, T, I, F)
include Iterator(T)
include IteratorWrapper
@iterator : I0
@func : F
@nest_iterator : I?
@stopped : Array(I)
def initialize(@iterator, @func)
@nest_iterator = nil
@stopped = [] of I
end
def next
if iter = @nest_iterator
value = iter.next
if value.is_a?(Stop)
@stopped << iter
@nest_iterator = nil
self.next
else
value
end
else
case value = @func.call wrapped_next
when Array
@nest_iterator = value.each
self.next
when Iterator
@nest_iterator = value
self.next
else
value
end
end
end
def self.element_type(iter, func)
value = iter.next
raise "" if value.is_a?(Stop)
case value = func.call value
when Array, Iterator
value.first
else
value
end
end
def self.iterator_type(iter, func)
value = iter.next
raise "" if value.is_a?(Stop)
case value = func.call value
when Array
value.each
when Iterator
value
else
raise ""
end
end
end
# Returns an iterator that chunks the iterator's elements in arrays of *size*
# filling up the remaining elements if no element remains with `nil` or a given
# optional parameter.
#
# ```
# iter = (1..3).each.in_groups_of(2)
# iter.next # => [1, 2]
# iter.next # => [3, nil]
# iter.next # => Iterator::Stop::INSTANCE
# ```
# ```
# iter = (1..3).each.in_groups_of(2, 'z')
# iter.next # => [1, 2]
# iter.next # => [3, 'z']
# iter.next # => Iterator::Stop::INSTANCE
# ```
#
# By default, a new array is created and yielded for each group.
# * If *reuse* is given, the array can be reused
# * If *reuse* is an `Array`, this array will be reused
# * If *reuse* is truthy, the method will create a new array and reuse it.
#
# This can be used to prevent many memory allocations when each slice of
# interest is to be used in a read-only fashion.
def in_groups_of(size : Int, filled_up_with = nil, reuse = false)
raise ArgumentError.new("Size must be positive") if size <= 0
InGroupsOfIterator(typeof(self), T, typeof(size), typeof(filled_up_with)).new(self, size, filled_up_with, reuse)
end
private struct InGroupsOfIterator(I, T, N, U)
include Iterator(Array(T | U))
include IteratorWrapper
@reuse : Array(T | U)?
def initialize(@iterator : I, @size : N, @filled_up_with : U, reuse)
if reuse
if reuse.is_a?(Array)
@reuse = reuse
else
@reuse = Array(T | U).new(@size)
end
else
@reuse = nil
end
end
def next
value = wrapped_next
if reuse = @reuse
reuse.clear
array = reuse
else
array = Array(T | U).new(@size)
end
array << value
(@size - 1).times do
new_value = @iterator.next
new_value = @filled_up_with if new_value.is_a?(Stop)
array << new_value
end
array
end
end
# Returns an iterator that applies the given block to the next element and
# returns the result.
#
# ```
# iter = [1, 2, 3].each.map &.*(2)
# iter.next # => 2
# iter.next # => 4
# iter.next # => 6
# iter.next # => Iterator::Stop::INSTANCE
# ```
def map(&func : T -> U) forall U
MapIterator(typeof(self), T, U).new(self, func)
end
private struct MapIterator(I, T, U)
include Iterator(U)
include IteratorWrapper
def initialize(@iterator : I, @func : T -> U)
end
def next
value = wrapped_next
@func.call(value)
end
end
# Returns an iterator that only returns elements for which the passed in
# block returns a falsey value.
#
# ```
# iter = [1, 2, 3].each.reject &.odd?
# iter.next # => 2
# iter.next # => Iterator::Stop::INSTANCE
# ```
def reject(&func : T -> U) forall U
RejectIterator(typeof(self), T, U).new(self, func)
end
# Returns an iterator that only returns elements
# that are **not** of the given *type*.
#
# ```
# iter = [1, false, 3, true].each.reject(Bool)
# iter.next # => 1
# iter.next # => 3
# iter.next # => Iterator::Stop::INSTANCE
# ```
def reject(type : U.class) forall U
SelectTypeIterator(typeof(self), typeof(begin
e = first
e.is_a?(U) ? raise("") : e
end)).new(self)
end
# Returns an iterator that only returns elements
# where `pattern === element` does not hold.
#
# ```
# iter = [2, 3, 1, 5, 4, 6].each.reject(3..5)
# iter.next # => 2
# iter.next # => 1
# iter.next # => 6
# iter.next # => Iterator::Stop::INSTANCE
# ```
def reject(pattern)
reject { |elem| pattern === elem }
end
private struct RejectIterator(I, T, B)
include Iterator(T)
include IteratorWrapper
def initialize(@iterator : I, @func : T -> B)
end
def next
while true
value = wrapped_next
unless @func.call(value)
return value
end
end
end
end
# Returns an iterator that only returns elements for which the passed
# in block returns a truthy value.
#
# ```
# iter = [1, 2, 3].each.select &.odd?
# iter.next # => 1
# iter.next # => 3
# iter.next # => Iterator::Stop::INSTANCE
# ```
def select(&func : T -> U) forall U