/
stream.go
1260 lines (1085 loc) · 33.2 KB
/
stream.go
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
package stream
// SPDX-License-Identifier: Apache-2.0
import (
"fmt"
gomath "math"
"math/bits"
"reflect"
"sync"
"github.com/bantling/micro/constraint"
"github.com/bantling/micro/conv"
"github.com/bantling/micro/funcs"
"github.com/bantling/micro/iter"
"github.com/bantling/micro/math"
"github.com/bantling/micro/tuple"
)
// PUnit indicates how to interpret a parallel quantity
type PUnit bool
const (
Threads PUnit = false // NumThreads indicates the quantity is the number of threads
Items PUnit = true // NumItems indicates the quantity is the number of items each thread processes
)
// PInfo includes the number of items and a unit
type PInfo struct {
N int
PUnit
}
// Constants
var (
absErrMsg = "Absolute value error for %d: there is no corresponding positive value in type %T"
)
// ==== Functions that provide the foundation for all other functions
// Map constructs a new Iter[U] from an Iter[T] and a func that transforms a T to a U.
//
// The resulting iter can return any kind of error from source iter, or EOI.
func Map[T, U any](mapper func(T) U) func(iter.Iter[T]) iter.Iter[U] {
return func(it iter.Iter[T]) iter.Iter[U] {
return iter.OfIter(func() (U, error) {
val, err := it.Next()
if err == nil {
return mapper(val), nil
}
var zv U
return zv, err
})
}
}
// MapError is similar to Map, except the mapper function returns (U, error), and the first element that returns a non-nil
// error results in iteration being cut short.
//
// The resulting iter can return any kind of error from source iter, or EOI.
func MapError[T, U any](mapper func(T) (U, error)) func(iter.Iter[T]) iter.Iter[U] {
return func(it iter.Iter[T]) iter.Iter[U] {
return iter.OfIter(func() (U, error) {
val, err := it.Next()
if err == nil {
var mval U
if mval, err = mapper(val); err == nil {
return mval, nil
}
}
var zv U
return zv, err
})
}
}
// Filter constructs a new Iter[T] from an Iter[T] and a func that returns true if a T passes the filter.
//
// The resulting iter can return any kind of error from source iter, or EOI.
func Filter[T any](filter func(T) bool) func(iter.Iter[T]) iter.Iter[T] {
return func(it iter.Iter[T]) iter.Iter[T] {
return iter.OfIter(func() (T, error) {
var (
val T
err error
)
for {
val, err = it.Next()
if err == nil {
if filter(val) {
return val, nil
}
} else {
break
}
}
var zv T
return zv, err
})
}
}
// Reduce reduces all elements in the input set to an empty or single element output set, depending on two factors:
// - the number of elements in the input set (0, 1, or multiple)
// - whether or not the optional identity is provided
//
// If the optional identity is NOT provided:
// - 0 elements: empty
// - 1 element: the element
// - multiple elements: reducer(reducer(reducer(first, second), third), ...)
//
// If the optional identity IS provided:
//
// - 0 elements: identity
// - 1 element: reducer(identity, the element)
// - multiple elements: reducer(reducer(reducer(identity, first), second), ...)
//
// The resulting iter can return any kind of error from source iter, or EOI.
func Reduce[T any](
reducer func(T, T) T,
identity ...T,
) func(iter.Iter[T]) iter.Iter[T] {
return func(it iter.Iter[T]) iter.Iter[T] {
var done bool
return iter.OfIter(func() (T, error) {
var (
val T
zv T
err error
)
if done {
return zv, iter.EOI
}
done = true
if len(identity) == 0 {
// No identity
val, err = it.Next()
if err != nil {
// 0 elements = Empty set, return error that may be EOI or a problem
return zv, err
} else {
// At least one element, start with first element
result := val
for {
val, err = it.Next()
if err == nil {
// If there are more elements, make cumulative reducer calls
result = reducer(result, val)
} else if err != iter.EOI {
// A problem occurred, toss result
return zv, err
} else {
// An EOI occurred
break
}
}
// Successfully return result
return result, nil
}
}
// There is an identity
identityVal := identity[0]
val, err = it.Next()
if err != nil {
if err == iter.EOI {
// 0 elements = identity
return identityVal, nil
}
// A problem
return zv, err
} else {
// At least one element, call reducer with identity and first element
result := reducer(identityVal, val)
for {
val, err = it.Next()
if err == nil {
// If there are more elements, make cumulative reducer calls
result = reducer(result, val)
} else if err != iter.EOI {
// A problem occurred, toss result
return zv, err
} else {
// An EOI occurred
break
}
}
// Successfully return result
return result, nil
}
})
}
}
// ReduceTo is similar to Reduce, except that the result does not have to be the same type
// The resulting iter can return any kind of error from source iter, or EOI.
func ReduceTo[T, U any](
reducer func(U, T) U,
identity ...U,
) func(iter.Iter[T]) iter.Iter[U] {
return func(it iter.Iter[T]) iter.Iter[U] {
var done bool
return iter.OfIter(func() (U, error) {
var (
val T
zv U
err error
)
if done {
return zv, iter.EOI
}
done = true
if len(identity) == 0 {
// No identity
val, err = it.Next()
if err != nil {
// 0 elements = Empty set, return error that may be EOI or a problem
return zv, err
} else {
// At least one element, call reducer with zero value and first element
result := reducer(zv, val)
for {
val, err = it.Next()
if err == nil {
// If there are more elements, make cumulative reducer calls, combining old and new results
result = reducer(result, val)
} else if err != iter.EOI {
// A problem occurred, toss result
return zv, err
} else {
// An EOI occurred
break
}
}
// Successfully return result
return result, nil
}
}
// There is an identity
identityVal := identity[0]
val, err = it.Next()
if err != nil {
if err == iter.EOI {
// 0 elements = identity
return identityVal, nil
}
// A problem
return zv, err
} else {
// At least one element, call reducer with identity and first element
result := reducer(identityVal, val)
for {
val, err = it.Next()
if err == nil {
// If there are more elements, make cumulative reducer calls
result = reducer(result, val)
} else if err != iter.EOI {
// A problem occurred, toss result
return zv, err
} else {
// An EOI occurred
break
}
}
// Successfully return result
return result, nil
}
})
}
}
// ReduceToBool is similar to ReduceTo, except that it uses boolean short circuit logic to stop iterating early if
// possible. If stopVal is true, then early termination occurs on the first call to reducer that returns true, else it
// occurs on the first call to reducer that returns false.
func ReduceToBool[T any](
predicate func(T) bool,
identity bool,
stopVal bool,
) func(iter.Iter[T]) iter.Iter[bool] {
return func(it iter.Iter[T]) iter.Iter[bool] {
var done bool
return iter.OfIter(func() (bool, error) {
if done {
return false, iter.EOI
}
done = true
var (
val T
err error
)
val, err = it.Next()
if err != nil {
if err == iter.EOI {
// 0 elements = identity
return identity, nil
}
// A problem occurred
return false, err
} else {
// At least one element, call reducer with identity and first element
result := predicate(val)
if result == stopVal {
// Stop early if result matches stopping condition
return result, nil
}
for {
val, err = it.Next()
if err != nil {
if err == iter.EOI {
// Successfully return result
break
}
// A problem
return false, err
}
// If there are more elements, call predicate
result = predicate(val)
if result == stopVal {
// Stop early if result matches stopping condition
return result, nil
}
}
// Successfully return result
return result, nil
}
})
}
}
// ReduceToSlice reduces an Iter[T] into a Iter[[]T] that contains a single element of type []T.
// Eg, an Iter[int] of 1,2,3,4,5 becomes an Iter[[]int] of [1,2,3,4,5].
// An empty Iter is reduced to a zero length slice.
func ReduceToSlice[T any](it iter.Iter[T]) iter.Iter[[]T] {
var done bool
return iter.OfIter(func() ([]T, error) {
if done {
return nil, iter.EOI
}
done = true
var (
val T
err error
slc = []T{}
)
for {
val, err = it.Next()
if err != nil {
if err == iter.EOI {
// Successfully iterated all values
break
}
// A problem
var zv []T
return zv, err
}
// Append element
slc = append(slc, val)
}
// Successfully return result
return slc, nil
})
}
// ReduceIntoSlice is the same as ReduceToSlice, except that:
// - It accepts a target slice to append results to
// - It generates a transform
//
// The generated transform panics if the target slice length is not at least as many elements as the source iter.
// If the underlying iter returns a non-nil non-EOI error, the provided slice will have zero values.
func ReduceIntoSlice[T any](slc []T) func(iter.Iter[T]) iter.Iter[[]T] {
return func(it iter.Iter[T]) iter.Iter[[]T] {
var (
done bool
i int
)
return iter.OfIter(func() ([]T, error) {
if done {
return nil, iter.EOI
}
done = true
var (
val T
err error
)
for {
val, err = it.Next()
if err != nil {
if err == iter.EOI {
// Successfully iterated all values
break
}
// A problem
var zv T
for i := range slc {
slc[i] = zv
}
return slc, err
}
// Set next slice index
slc[i] = val
i++
}
// Successfully return result
return slc, nil
})
}
}
// ExpandSlices is the opposite of ReduceToSlice: an Iter[[]int] of [1,2,3,4,5] becomes an Iter[int] of 1,2,3,4,5.
// If the source Iter contains multiple slices, they are combined together into one set of data (skipping nil and empty
// slices), so that an Iter[[]int] of [1,2,3], nil, [], [4,5] also becomes an Iter[int] of 1,2,3,4,5.
// An empty Iter or an Iter with nil/empty slices is expanded to an empty Iter.
func ExpandSlices[T any](it iter.Iter[[]T]) iter.Iter[T] {
var (
slc []T
idx int
)
return iter.OfIter(func() (T, error) {
if (slc == nil) || (idx == len(slc)) {
// Search for next non-nil non-empty slice
// Nilify slc var in case we just finished iterating last element of last slice, which is non-nil
slc = nil
var (
zv T
err error
)
for {
slc, err = it.Next()
if err != nil {
if err == iter.EOI {
// Successfully iterated all values - slc shd be nil, but make sure
slc = nil
break
}
// A problem
return zv, err
}
if (slc != nil) && (len(slc) > 0) {
// Found a non-empty slice
idx = 0
break
}
}
// Stop if no more non-nil non-empty slices available
if slc == nil {
return zv, iter.EOI
}
}
// Successfully acquired an index of a slice to return
val := slc[idx]
idx++
return val, nil
})
}
// ReduceToMap reduces an Iter[tuple.Two[K, V]]] into a Iter[map[K, V]] that contains a single element if type map[K, V].
// Eg, an Iter[tuple.Two[int]string] of {1: "1"}, {2: "2"} becomes an Iter[map[int]string] of {1: "1", 2: "2"}.
// If multiple tuple.Two objects in the Iter have the same key, the last such object in iteration order determines the
// value for the key in the resulting map.
// An empty Iter is reduced to an empty map.
func ReduceToMap[K comparable, V any](it iter.Iter[tuple.Two[K, V]]) iter.Iter[map[K]V] {
var done bool
return iter.OfIter(func() (map[K]V, error) {
if done {
return nil, iter.EOI
}
done = true
var (
m = map[K]V{}
kv tuple.Two[K, V]
err error
)
for {
kv, err = it.Next()
if err != nil {
if err == iter.EOI {
// Successfully iterated all values
break
}
// A problem
var zv map[K]V
return zv, err
}
// Successfully acquired a key value pair to put into the map
m[kv.T] = kv.U
}
return m, nil
})
}
// ExpandMaps is the opposite of ReduceToMap: an Iter[map[int]string] of {1: "1", 2: "2", 3: "3"} becomes an
// Iter[tuple.Two[int, string]] of {1: "1"}, {2: "2"}, {3: "3"].
// If the source Iter contains multiple maps, they are combined together into one set of data (skipping nils),
// so that an Iter[map[int]string] of {1: "1", 2: "2"}, nil, {}, {3: "3"} also becomes
// an Iter[tuple.Two[int, string]] of {1: "1"}, {2: "2"}, {3: "3"}.
// An empty Iter or an Iter with nil/empty maps is expanded to an empty Iter.
func ExpandMaps[K comparable, V any](it iter.Iter[map[K]V]) iter.Iter[tuple.Two[K, V]] {
var (
m map[K]V
mr *reflect.MapIter
)
return iter.OfIter(func() (tuple.Two[K, V], error) {
var (
zv tuple.Two[K, V]
err error
)
if (m == nil) || (!mr.Next()) {
// Search for next non-nil non-empty map
// Nilify m var in case last call finished iterating last element of last map
m = nil
for {
m, err = it.Next()
if err != nil {
if err == iter.EOI {
// Unable to find next result, nilify m
m = nil
break
}
// A problem
return zv, err
}
if m != nil {
// Found non-nil map, see if it is also non-empty
if mr = reflect.ValueOf(m).MapRange(); mr.Next() {
break
}
}
}
// Stop if no more non-nil non-empty maps available
if m == nil {
return zv, iter.EOI
}
}
val := tuple.Of2(mr.Key().Interface().(K), mr.Value().Interface().(V))
return val, nil
})
}
// Skip skips the first n elements, then iteration continues from there.
// If there are n or fewer elements in total, then the resulting iter is empty.
//
// Note that for the set 1,2,3,4,5 the composition os Skip(1),Limit(3) will first skip 1 then limit to 2,3,4;
// whereas the composition of Limit(3),Skip(1) will first limit to 1,2,3 then skip 1 returning 2,3.
func Skip[T any](n uint) func(iter.Iter[T]) iter.Iter[T] {
return func(it iter.Iter[T]) iter.Iter[T] {
skip := n
return iter.OfIter(func() (T, error) {
var (
val T
zv T
err error
)
// Skip first n values only once
for skip > 0 {
val, err = it.Next()
if err != nil {
// Reached end or problem
skip = 0
return zv, err
}
// Read a value to skip
skip--
}
val, err = it.Next()
if err != nil {
// Reached end or problem
return zv, err
}
// Successfully read a value to return
return val, nil
})
}
}
// Limit returns the first n elements, then iteration stops and all further elements are ignored.
// If there fewer than n elements in total, then all n elements are returned.
//
// Note that for the set 1,2,3,4,5 the composition of Skip(1),Limit(3) will first skip 1 then limit to 2,3,4;
// whereas the composition of Limit(3),Skip(1) will first limit to 1,2,3 then skip 1 returning 2,3.
func Limit[T any](n uint) func(iter.Iter[T]) iter.Iter[T] {
return func(it iter.Iter[T]) iter.Iter[T] {
limit := n
return iter.OfIter(func() (T, error) {
var (
val T
zv T
err error
)
if limit > 0 {
// Try to get next value that is within the limit
val, err = it.Next()
if err != nil {
// EOI or problem
return zv, err
}
// Successfully read value, decrement limit for next time
limit--
return val, nil
}
// Limit = 0, do not read any more values
return zv, iter.EOI
})
}
}
// Peek executes a func for every item being iterated, which is a side effect.
func Peek[T any](fn func(T)) func(iter.Iter[T]) iter.Iter[T] {
return func(it iter.Iter[T]) iter.Iter[T] {
return iter.OfIter(func() (T, error) {
// Read next value
val, err := it.Next()
if err != nil {
// EOI or problem
var zv T
return zv, err
}
// Successfully found a value
fn(val)
return val, nil
})
}
}
// Generator receives a generator (a func of no args that returns a func of Iter[T] -> Iter[U], and detects if the
// Iter[T] has changed address. If so, it internally generates a new function by invoking the generator.
//
// This allows stateful transforms of Iter[T] -> Iter[U] that track state across calls to begin with a new initial state
// for each data set the transform is applied to.
//
// Generator is not thread safe, so be careful about storing a composition containing a Generator in a global variable:
// 1. Declare the global variable as a function of no args that generates the composition when executed
// 2. Declare composition in a local variable so each thread makes its own copy
// 3. Store composition in a Context that is visible across methods in the thread
//
// See Distinct for an example of a stateful function that uses Generator internally.
func Generator[T, U any](gen func() func(iter.Iter[T]) iter.Iter[U]) func(iter.Iter[T]) iter.Iter[U] {
var (
currentIter iter.Iter[T]
fn func(iter.Iter[T]) iter.Iter[U]
)
return func(it iter.Iter[T]) iter.Iter[U] {
if currentIter != it {
fn = gen()
}
return fn(it)
}
}
// ==== Functions based on foundational functions
// AllMatch reduces Iter[T] to an Iter[bool] with a single value that is true if the Iter[T] is empty or all elements
// pass the filter. Boolean short circuit logic stops on first case where filter returns false.
// Calls ReduceToBool(filter, true, false).
func AllMatch[T any](filter func(T) bool) func(iter.Iter[T]) iter.Iter[bool] {
return ReduceToBool(filter, true, false)
}
// AnyMatch reduces Iter[T] to an Iter[bool] with a single value that is true if the Iter[T] is non-empty and any
// element passes the filter. Boolean short circuit logic stops on first case where filter returns true.
// Calls ReduceToBool(filter, true, false).
func AnyMatch[T any](filter func(T) bool) func(iter.Iter[T]) iter.Iter[bool] {
return ReduceToBool(filter, false, true)
}
// NoneMatch reduces Iter[T] to an Iter[bool] with a single value that is true if the Iter[T] is empty or no elements
// pass the filter. Boolean short circuit logic stops on first case where filter returns true.
// Calls ReduceToBool(!filter, true, false).
func NoneMatch[T any](filter func(T) bool) func(iter.Iter[T]) iter.Iter[bool] {
return ReduceToBool(func(t T) bool { return !filter(t) }, true, false)
}
// Count reduces Iter[T] to an Iter[int] with a single value that is the number of elements in the Iter[T].
func Count[T any](it iter.Iter[T]) iter.Iter[int] {
return ReduceTo[T, int](func(c int, _ T) int { return c + 1 }, 0)(it)
}
// Distinct reduces Iter[T] to an Iter[T] with distinct values.
// Distinct is a stateful transform that has to track unique values across iterator Next and Value calls.
//
// Distinct uses Generator internally to ensure what whenever a new Iter is encountered, a new state of an empty set of
// values is generated. This allows a composition to be stored in a variable and reused across data sets correctly.
//
// If you want Distinct to have one state across multiple Iters, use Concat to create a single Iter that traverses them.
func Distinct[T comparable](it iter.Iter[T]) iter.Iter[T] {
return Generator(func() func(iter.Iter[T]) iter.Iter[T] {
vals := map[T]bool{}
return Filter[T](func(val T) bool {
haveIt := vals[val]
if !haveIt {
vals[val] = true
}
return !haveIt
})
})(it)
}
// Duplicate reduces Iter[T] to an Iter[T] with duplicate values.
// Like Distinct, a given duplicate will only appear once.
// The order of the elements is the order in which the second occurence of each value appears.
// Eg, for the input 1,2,2,1 the result is 2,1 since the second value of 2 appears before the second value of 1.
// See Distinct for an explanation of statefulness and the usage of Generator.
func Duplicate[T comparable](it iter.Iter[T]) iter.Iter[T] {
return Generator(func() func(iter.Iter[T]) iter.Iter[T] {
vals := map[T]int{}
return Filter[T](func(val T) bool {
count := vals[val]
if count < 3 {
count++
vals[val] = count
}
return count == 2
})
})(it)
}
// Reverse reverses all the elements.
// The input iter must have a finite size.
func Reverse[T any](it iter.Iter[T]) iter.Iter[T] {
// Get values into a slice
slc, err := ReduceToSlice(it).Next()
if err != nil {
// Unable to get any values to reverse
return iter.SetError(iter.OfEmpty[T](), err)
}
// Reverse elements
funcs.SliceReverse(slc)
// Return iterator of reversed elements
return iter.OfSlice(slc)
}
// SortOrdered sorts an Ordered type that is implicitly sortable using funcs.SliceSortOrdered.
// The input iter must have a finite size.
func SortOrdered[T constraint.Ordered](it iter.Iter[T]) iter.Iter[T] {
// Get values into a slice
slc, err := ReduceToSlice(it).Next()
if err != nil {
// Unable to get any values to sort
return iter.SetError(iter.OfEmpty[T](), err)
}
// Sort elements
funcs.SliceSortOrdered(slc)
// Successfully return sorted iter
return iter.OfSlice(slc)
}
// SortComplex sorts a Complex type using funcs.SliceSortComplex.
// The input iter must have a finite size.
func SortComplex[T constraint.Complex](it iter.Iter[T]) iter.Iter[T] {
// Get values into a slice
slc, err := ReduceToSlice(it).Next()
if err != nil {
// Unable to get any values to sort
return iter.SetError(iter.OfEmpty[T](), err)
}
// Sort elements
funcs.SliceSortComplex(slc)
// Successfully return sorted iter
return iter.OfSlice(slc)
}
// SortCmp sorts a Cmp type using funcs.SliceSortCmp.
// The input iter must have a finite size.
func SortCmp[T constraint.Cmp[T]](it iter.Iter[T]) iter.Iter[T] {
// Get values into a slice
slc, err := ReduceToSlice(it).Next()
if err != nil {
// Unable to get any values to sort
return iter.SetError(iter.OfEmpty[T](), err)
}
// Sort elements
funcs.SliceSortCmp(slc)
// Successfully return sorted iter
return iter.OfSlice(slc)
}
// SortBy sorts any type using funcs.SliceSortBy and the given comparator.
// The input iter must have a finite size.
func SortBy[T any](less func(T, T) bool) func(iter.Iter[T]) iter.Iter[T] {
return func(it iter.Iter[T]) iter.Iter[T] {
// Get values into a slice
slc, err := ReduceToSlice(it).Next()
if err != nil {
// Unable to get any values to sort
return iter.SetError(iter.OfEmpty[T](), err)
}
// Sort elements
funcs.SliceSortBy(slc, less)
// Successfully return sorted iter
return iter.OfSlice(slc)
}
}
// ==== Math
// Abs converts all elements into their absolute values.
// See MapError for error handling in cases where there is no corresponding value for a negative integer.
func Abs[T constraint.SignedInteger](it iter.Iter[T]) iter.Iter[T] {
return MapError(func(v T) (T, error) {
if v < 0 {
if v = -v; v < 0 {
var zv T
return zv, fmt.Errorf(absErrMsg, v, v)
}
}
return v, nil
})(it)
}
// AbsBigOps is the *big.Int, *big.Float, *big.Rat specialization of Abs
func AbsBigOps[T constraint.BigOps[T]](it iter.Iter[T]) iter.Iter[T] {
return Map(func(v T) T {
return v.Abs(v)
})(it)
}
// AvgInt reduces all signed integer elements in the input set to their average. If the input set is empty, the result is empty.
// The average is rounded.
// See math.Add, math.Div.
func AvgInt[T constraint.SignedInteger](it iter.Iter[T]) iter.Iter[T] {
return iter.OfIter(
func() (T, error) {
var (
sum T
count int64
val T
avg T
zv T
err error
)
for {
if val, err = it.Next(); err == nil {
// Sum all values and count them, checking for over/underflow
if err = math.AddInt(val, &sum); err != nil {
return zv, err
}
count++
} else if err == iter.EOI {
if count == 0 {
// Empty result
return zv, err
}
// Non-empty result - divisor = zero handled above, so Div will never fail
var de, q int64
conv.To(sum, &de)
math.Div(de, count, &q)
conv.To(q, &avg)
break
} else {
return zv, err
}
}
return avg, nil
},
)
}
// AvgUint reduces all unsigned integer elements in the input set to their average. If the input set is empty, the result is empty.
// The average is rounded.
// See math.Add, math.Div.
func AvgUint[T constraint.UnsignedInteger](it iter.Iter[T]) iter.Iter[T] {
return iter.OfIter(
func() (T, error) {
var (
sum T
count uint64
val T
avg T
zv T
err error
)
for {
if val, err = it.Next(); err == nil {
// Sum all values and count them, checking for overflow
if err = math.AddUint(val, &sum); err != nil {
return zv, err
}
count++
} else if err == iter.EOI {
if count == 0 {
// Empty result
return zv, err
}
// Non-empty result - divisor = zero handled above, so Div will never fail
var de, q uint64
conv.To(sum, &de)
math.Div(de, count, &q)
conv.To(q, &avg)
break
} else {
return zv, err
}
}
return avg, nil
},
)
}
// AvgBigOps reduces all *big.Int, *big.Float, or *big.Rat elements in the input set to their average.
// If the input set is empty, the result is empty. The average is rounded only for *big.Int.
// See math.DivBigOps
func AvgBigOps[T constraint.BigOps[T]](it iter.Iter[T]) iter.Iter[T] {
return iter.OfIter(