forked from JetBrains/kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAggregates.kt
977 lines (883 loc) · 32.9 KB
/
Aggregates.kt
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
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package templates
import templates.Family.*
import templates.SequenceClass.*
object Aggregates : TemplateGroupBase() {
init {
defaultBuilder {
if (sequenceClassification.isEmpty()) {
sequenceClassification(terminal)
}
specialFor(ArraysOfUnsigned) {
since("1.3")
annotation("@ExperimentalUnsignedTypes")
}
}
}
val f_all = fn("all(predicate: (T) -> Boolean)") {
includeDefault()
include(Maps, CharSequences, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc {
"""
Returns `true` if all ${f.element.pluralize()} match the given [predicate].
"""
}
sample("samples.collections.Collections.Aggregates.all")
returns("Boolean")
body {
"""
${when (f) {
Iterables -> "if (this is Collection && isEmpty()) return true"
Maps -> "if (isEmpty()) return true"
else -> ""
}}
for (element in this) if (!predicate(element)) return false
return true
"""
}
}
val f_none_predicate = fn("none(predicate: (T) -> Boolean)") {
includeDefault()
include(Maps, CharSequences, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc {
"""
Returns `true` if no ${f.element.pluralize()} match the given [predicate].
"""
}
sample("samples.collections.Collections.Aggregates.noneWithPredicate")
returns("Boolean")
body {
"""
${when (f) {
Iterables -> "if (this is Collection && isEmpty()) return true"
Maps -> "if (isEmpty()) return true"
else -> ""
}}
for (element in this) if (predicate(element)) return false
return true
"""
}
}
val f_none = fn("none()") {
includeDefault()
include(Maps, CharSequences, ArraysOfUnsigned)
} builder {
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc {
"""
Returns `true` if the ${f.collection} has no ${f.element.pluralize()}.
"""
}
sample("samples.collections.Collections.Aggregates.none")
returns("Boolean")
body {
"return !iterator().hasNext()"
}
specialFor(Iterables) {
body {
"""
if (this is Collection) return isEmpty()
return !iterator().hasNext()
"""
}
}
body(Maps, CharSequences, ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned) {
"return isEmpty()"
}
}
val f_any_predicate = fn("any(predicate: (T) -> Boolean)") {
includeDefault()
include(Maps, CharSequences, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc {
"""
Returns `true` if at least one ${f.element} matches the given [predicate].
"""
}
sample("samples.collections.Collections.Aggregates.anyWithPredicate")
returns("Boolean")
body {
"""
${when (f) {
Iterables -> "if (this is Collection && isEmpty()) return false"
Maps -> "if (isEmpty()) return false"
else -> ""
}}
for (element in this) if (predicate(element)) return true
return false
"""
}
}
val f_any = fn("any()") {
includeDefault()
include(Maps, CharSequences, ArraysOfUnsigned)
} builder {
doc {
"""
Returns `true` if ${f.collection} has at least one ${f.element}.
"""
}
sample("samples.collections.Collections.Aggregates.any")
returns("Boolean")
body {
"return iterator().hasNext()"
}
body(Iterables) {
"""
if (this is Collection) return !isEmpty()
return iterator().hasNext()
"""
}
body(Maps, CharSequences, ArraysOfObjects, ArraysOfPrimitives) { "return !isEmpty()" }
specialFor(ArraysOfUnsigned) {
inlineOnly()
body { "return storage.any()" }
}
}
val f_count_predicate = fn("count(predicate: (T) -> Boolean)") {
includeDefault()
include(Maps, CharSequences, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc { "Returns the number of ${f.element.pluralize()} matching the given [predicate]." }
returns("Int")
body {
fun checkOverflow(value: String) = if (f == Sequences || f == Iterables) "checkCountOverflow($value)" else value
"""
${when (f) {
Iterables -> "if (this is Collection && isEmpty()) return 0"
Maps -> "if (isEmpty()) return 0"
else -> ""
}}
var count = 0
for (element in this) if (predicate(element)) ${checkOverflow("++count")}
return count
"""
}
}
val f_count = fn("count()") {
includeDefault()
include(Collections, Maps, CharSequences)
} builder {
doc { "Returns the number of ${f.element.pluralize()} in this ${f.collection}." }
returns("Int")
body {
fun checkOverflow(value: String) = if (f == Sequences || f == Iterables) "checkCountOverflow($value)" else value
"""
${if (f == Iterables) "if (this is Collection) return size" else ""}
var count = 0
for (element in this) ${checkOverflow("++count")}
return count
"""
}
specialFor(CharSequences, Maps, Collections, ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned) { inlineOnly() }
specialFor(CharSequences) {
doc { "Returns the length of this char sequence." }
body { "return length" }
}
body(Maps, Collections, ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned) {
"return size"
}
}
val f_sumBy = fn("sumBy(selector: (T) -> Int)") {
includeDefault()
include(CharSequences, ArraysOfUnsigned)
} builder {
inline()
doc { "Returns the sum of all values produced by [selector] function applied to each ${f.element} in the ${f.collection}." }
returns("Int")
body {
"""
var sum: Int = 0
for (element in this) {
sum += selector(element)
}
return sum
"""
}
specialFor(ArraysOfUnsigned) {
inlineOnly()
signature("sumBy(selector: (T) -> UInt)")
returns("UInt")
body {
"""
var sum: UInt = 0u
for (element in this) {
sum += selector(element)
}
return sum
"""
}
}
}
val f_sumByDouble = fn("sumByDouble(selector: (T) -> Double)") {
includeDefault()
include(CharSequences, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc { "Returns the sum of all values produced by [selector] function applied to each ${f.element} in the ${f.collection}." }
returns("Double")
body {
"""
var sum: Double = 0.0
for (element in this) {
sum += selector(element)
}
return sum
"""
}
}
val f_minMax = run {
val genericSpecializations = PrimitiveType.floatingPointPrimitives + setOf(null)
listOf("min", "max").map { op ->
fn("$op()") {
include(Iterables, genericSpecializations)
include(Sequences, genericSpecializations)
include(ArraysOfObjects, genericSpecializations)
include(ArraysOfPrimitives, PrimitiveType.defaultPrimitives - PrimitiveType.Boolean)
include(ArraysOfUnsigned)
include(CharSequences)
} builder {
val isFloat = primitive?.isFloatingPoint() == true
val isGeneric = f in listOf(Iterables, Sequences, ArraysOfObjects)
typeParam("T : Comparable<T>")
if (primitive != null) {
if (isFloat && isGeneric)
since("1.1")
}
doc {
"Returns the ${if (op == "max") "largest" else "smallest"} ${f.element} or `null` if there are no ${f.element.pluralize()}." +
if (isFloat) "\n\n" + "If any of ${f.element.pluralize()} is `NaN` returns `NaN`." else ""
}
returns("T?")
body {
"""
val iterator = iterator()
if (!iterator.hasNext()) return null
var $op = iterator.next()
${if (isFloat) "if ($op.isNaN()) return $op" else "\\"}
while (iterator.hasNext()) {
val e = iterator.next()
${if (isFloat) "if (e.isNaN()) return e" else "\\"}
if ($op ${if (op == "max") "<" else ">"} e) $op = e
}
return $op
"""
}
body(ArraysOfObjects, ArraysOfPrimitives, CharSequences, ArraysOfUnsigned) {
"""
if (isEmpty()) return null
var $op = this[0]
${if (isFloat) "if ($op.isNaN()) return $op" else "\\"}
for (i in 1..lastIndex) {
val e = this[i]
${if (isFloat) "if (e.isNaN()) return e" else "\\"}
if ($op ${if (op == "max") "<" else ">"} e) $op = e
}
return $op
"""
}
body {
body!!.replace(Regex("""^\s+\\\n""", RegexOption.MULTILINE), "") // remove empty lines ending with \
}
}
}
}
val f_minBy = fn("minBy(selector: (T) -> R)") {
includeDefault()
include(Maps, CharSequences, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc { "Returns the first ${f.element} yielding the smallest value of the given function or `null` if there are no ${f.element.pluralize()}." }
sample("samples.collections.Collections.Aggregates.minBy")
typeParam("R : Comparable<R>")
returns("T?")
body {
"""
val iterator = iterator()
if (!iterator.hasNext()) return null
var minElem = iterator.next()
if (!iterator.hasNext()) return minElem
var minValue = selector(minElem)
do {
val e = iterator.next()
val v = selector(e)
if (minValue > v) {
minElem = e
minValue = v
}
} while (iterator.hasNext())
return minElem
"""
}
body(CharSequences, ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned) {
"""
if (isEmpty()) return null
var minElem = this[0]
val lastIndex = this.lastIndex
if (lastIndex == 0) return minElem
var minValue = selector(minElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = selector(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
"""
}
body(Maps) {
"return entries.minBy(selector)"
}
}
val f_minWith = fn("minWith(comparator: Comparator<in T>)") {
includeDefault()
include(Maps, CharSequences, ArraysOfUnsigned)
} builder {
doc { "Returns the first ${f.element} having the smallest value according to the provided [comparator] or `null` if there are no ${f.element.pluralize()}." }
returns("T?")
body {
"""
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (comparator.compare(min, e) > 0) min = e
}
return min
"""
}
body(CharSequences, ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned) {
"""
if (isEmpty()) return null
var min = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (comparator.compare(min, e) > 0) min = e
}
return min
"""
}
body(Maps) { "return entries.minWith(comparator)" }
}
val f_maxBy = fn("maxBy(selector: (T) -> R)") {
includeDefault()
include(Maps, CharSequences, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc { "Returns the first ${f.element} yielding the largest value of the given function or `null` if there are no ${f.element.pluralize()}." }
sample("samples.collections.Collections.Aggregates.maxBy")
typeParam("R : Comparable<R>")
returns("T?")
body {
"""
val iterator = iterator()
if (!iterator.hasNext()) return null
var maxElem = iterator.next()
if (!iterator.hasNext()) return maxElem
var maxValue = selector(maxElem)
do {
val e = iterator.next()
val v = selector(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
} while (iterator.hasNext())
return maxElem
"""
}
body(CharSequences, ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned) {
"""
if (isEmpty()) return null
var maxElem = this[0]
val lastIndex = this.lastIndex
if (lastIndex == 0) return maxElem
var maxValue = selector(maxElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = selector(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
"""
}
specialFor(Maps) {
inlineOnly()
body { "return entries.maxBy(selector)" }
}
}
val f_maxWith = fn("maxWith(comparator: Comparator<in T>)") {
includeDefault()
include(Maps, CharSequences, ArraysOfUnsigned)
} builder {
doc { "Returns the first ${f.element} having the largest value according to the provided [comparator] or `null` if there are no ${f.element.pluralize()}." }
returns("T?")
body {
"""
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (comparator.compare(max, e) < 0) max = e
}
return max
"""
}
body(CharSequences, ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned) {
"""
if (isEmpty()) return null
var max = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (comparator.compare(max, e) < 0) max = e
}
return max
"""
}
specialFor(Maps) {
inlineOnly()
body { "return entries.maxWith(comparator)" }
}
}
val f_foldIndexed = fn("foldIndexed(initial: R, operation: (index: Int, acc: R, T) -> R)") {
includeDefault()
include(CharSequences)
include(ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc {
"""
Accumulates value starting with [initial] value and applying [operation] from left to right
to current accumulator value and each ${f.element} with its index in the original ${f.collection}.
@param [operation] function that takes the index of ${f.element.prefixWithArticle()}, current accumulator value
and the ${f.element} itself, and calculates the next accumulator value.
"""
}
typeParam("R")
returns("R")
body {
fun checkOverflow(value: String) = if (f == Sequences || f == Iterables) "checkIndexOverflow($value)" else value
"""
var index = 0
var accumulator = initial
for (element in this) accumulator = operation(${checkOverflow("index++")}, accumulator, element)
return accumulator
"""
}
}
val f_foldRightIndexed = fn("foldRightIndexed(initial: R, operation: (index: Int, T, acc: R) -> R)") {
include(CharSequences, Lists, ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc {
"""
Accumulates value starting with [initial] value and applying [operation] from right to left
to each ${f.element} with its index in the original ${f.collection} and current accumulator value.
@param [operation] function that takes the index of ${f.element.prefixWithArticle()}, the ${f.element} itself
and current accumulator value, and calculates the next accumulator value.
"""
}
typeParam("R")
returns("R")
body {
"""
var index = lastIndex
var accumulator = initial
while (index >= 0) {
accumulator = operation(index, get(index), accumulator)
--index
}
return accumulator
"""
}
body(Lists) {
"""
var accumulator = initial
if (!isEmpty()) {
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
val index = iterator.previousIndex()
accumulator = operation(index, iterator.previous(), accumulator)
}
}
return accumulator
"""
}
}
val f_fold = fn("fold(initial: R, operation: (acc: R, T) -> R)") {
includeDefault()
include(CharSequences)
include(ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc { "Accumulates value starting with [initial] value and applying [operation] from left to right to current accumulator value and each ${f.element}." }
typeParam("R")
returns("R")
body {
"""
var accumulator = initial
for (element in this) accumulator = operation(accumulator, element)
return accumulator
"""
}
}
val f_foldRight = fn("foldRight(initial: R, operation: (T, acc: R) -> R)") {
include(CharSequences, Lists, ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc { "Accumulates value starting with [initial] value and applying [operation] from right to left to each ${f.element} and current accumulator value." }
typeParam("R")
returns("R")
body {
"""
var index = lastIndex
var accumulator = initial
while (index >= 0) {
accumulator = operation(get(index--), accumulator)
}
return accumulator
"""
}
body(Lists) {
"""
var accumulator = initial
if (!isEmpty()) {
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
}
return accumulator
"""
}
}
val f_reduceIndexed = fn("reduceIndexed(operation: (index: Int, acc: T, T) -> T)") {
include(ArraysOfPrimitives, ArraysOfUnsigned, CharSequences)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc {
"""
Accumulates value starting with the first ${f.element} and applying [operation] from left to right
to current accumulator value and each ${f.element} with its index in the original ${f.collection}.
@param [operation] function that takes the index of ${f.element.prefixWithArticle()}, current accumulator value
and the ${f.element} itself and calculates the next accumulator value.
"""
}
returns("T")
body {
"""
if (isEmpty())
throw UnsupportedOperationException("Empty ${f.doc.collection} can't be reduced.")
var accumulator = this[0]
for (index in 1..lastIndex) {
accumulator = operation(index, accumulator, this[index])
}
return accumulator
"""
}
}
val f_reduceIndexedSuper = fn("reduceIndexed(operation: (index: Int, acc: S, T) -> S)") {
include(ArraysOfObjects, Iterables, Sequences)
} builder {
inline()
doc {
"""
Accumulates value starting with the first ${f.element} and applying [operation] from left to right
to current accumulator value and each ${f.element} with its index in the original ${f.collection}.
@param [operation] function that takes the index of ${f.element.prefixWithArticle()}, current accumulator value
and the ${f.element} itself and calculates the next accumulator value.
"""
}
typeParam("S")
typeParam("T : S")
returns("S")
body {
fun checkOverflow(value: String) = if (f == Sequences || f == Iterables) "checkIndexOverflow($value)" else value
"""
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty ${f.doc.collection} can't be reduced.")
var index = 1
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(${checkOverflow("index++")}, accumulator, iterator.next())
}
return accumulator
"""
}
body(ArraysOfObjects) {
"""
if (isEmpty())
throw UnsupportedOperationException("Empty ${f.doc.collection} can't be reduced.")
var accumulator: S = this[0]
for (index in 1..lastIndex) {
accumulator = operation(index, accumulator, this[index])
}
return accumulator
"""
}
}
val f_reduceRightIndexed = fn("reduceRightIndexed(operation: (index: Int, T, acc: T) -> T)") {
include(CharSequences, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc {
"""
Accumulates value starting with last ${f.element} and applying [operation] from right to left
to each ${f.element} with its index in the original ${f.collection} and current accumulator value.
@param [operation] function that takes the index of ${f.element.prefixWithArticle()}, the ${f.element} itself
and current accumulator value, and calculates the next accumulator value.
"""
}
returns("T")
body {
"""
var index = lastIndex
if (index < 0) throw UnsupportedOperationException("Empty ${f.doc.collection} can't be reduced.")
var accumulator = get(index--)
while (index >= 0) {
accumulator = operation(index, get(index), accumulator)
--index
}
return accumulator
"""
}
}
val f_reduceRightIndexedSuper = fn("reduceRightIndexed(operation: (index: Int, T, acc: S) -> S)") {
include(Lists, ArraysOfObjects)
} builder {
inline()
doc {
"""
Accumulates value starting with last ${f.element} and applying [operation] from right to left
to each ${f.element} with its index in the original ${f.collection} and current accumulator value.
@param [operation] function that takes the index of ${f.element.prefixWithArticle()}, the ${f.element} itself
and current accumulator value, and calculates the next accumulator value.
"""
}
typeParam("S")
typeParam("T : S")
returns("S")
body {
"""
var index = lastIndex
if (index < 0) throw UnsupportedOperationException("Empty ${f.doc.collection} can't be reduced.")
var accumulator: S = get(index--)
while (index >= 0) {
accumulator = operation(index, get(index), accumulator)
--index
}
return accumulator
"""
}
body(Lists) {
"""
val iterator = listIterator(size)
if (!iterator.hasPrevious())
throw UnsupportedOperationException("Empty list can't be reduced.")
var accumulator: S = iterator.previous()
while (iterator.hasPrevious()) {
val index = iterator.previousIndex()
accumulator = operation(index, iterator.previous(), accumulator)
}
return accumulator
"""
}
}
val f_reduce = fn("reduce(operation: (acc: T, T) -> T)") {
include(ArraysOfPrimitives, ArraysOfUnsigned, CharSequences)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc { "Accumulates value starting with the first ${f.element} and applying [operation] from left to right to current accumulator value and each ${f.element}." }
returns("T")
body {
"""
if (isEmpty())
throw UnsupportedOperationException("Empty ${f.doc.collection} can't be reduced.")
var accumulator = this[0]
for (index in 1..lastIndex) {
accumulator = operation(accumulator, this[index])
}
return accumulator
"""
}
}
val f_reduceSuper = fn("reduce(operation: (acc: S, T) -> S)") {
include(ArraysOfObjects, Iterables, Sequences)
} builder {
inline()
doc { "Accumulates value starting with the first ${f.element} and applying [operation] from left to right to current accumulator value and each ${f.element}." }
typeParam("S")
typeParam("T : S")
returns("S")
body {
"""
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty ${f.doc.collection} can't be reduced.")
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(accumulator, iterator.next())
}
return accumulator
"""
}
body(ArraysOfObjects) {
"""
if (isEmpty())
throw UnsupportedOperationException("Empty ${f.doc.collection} can't be reduced.")
var accumulator: S = this[0]
for (index in 1..lastIndex) {
accumulator = operation(accumulator, this[index])
}
return accumulator
"""
}
}
val f_reduceRight = fn("reduceRight(operation: (T, acc: T) -> T)") {
include(CharSequences, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc { "Accumulates value starting with last ${f.element} and applying [operation] from right to left to each ${f.element} and current accumulator value." }
returns("T")
body {
"""
var index = lastIndex
if (index < 0) throw UnsupportedOperationException("Empty ${f.doc.collection} can't be reduced.")
var accumulator = get(index--)
while (index >= 0) {
accumulator = operation(get(index--), accumulator)
}
return accumulator
"""
}
}
val f_reduceRightSuper = fn("reduceRight(operation: (T, acc: S) -> S)") {
include(Lists, ArraysOfObjects)
} builder {
inline()
doc { "Accumulates value starting with last ${f.element} and applying [operation] from right to left to each ${f.element} and current accumulator value." }
typeParam("S")
typeParam("T : S")
returns("S")
body {
"""
var index = lastIndex
if (index < 0) throw UnsupportedOperationException("Empty ${f.doc.collection} can't be reduced.")
var accumulator: S = get(index--)
while (index >= 0) {
accumulator = operation(get(index--), accumulator)
}
return accumulator
"""
}
body(Lists) {
"""
val iterator = listIterator(size)
if (!iterator.hasPrevious())
throw UnsupportedOperationException("Empty list can't be reduced.")
var accumulator: S = iterator.previous()
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
return accumulator
"""
}
}
val f_onEach = fn("onEach(action: (T) -> Unit)") {
include(Iterables, Maps, CharSequences, Sequences)
} builder {
since("1.1")
specialFor(Iterables, Maps, CharSequences) {
inline()
doc { "Performs the given [action] on each ${f.element} and returns the ${f.collection} itself afterwards." }
val collectionType = when (f) {
Maps -> "M"
CharSequences -> "S"
else -> "C"
}
receiver(collectionType)
returns(collectionType)
typeParam("$collectionType : SELF")
body { "return apply { for (element in this) action(element) }" }
}
specialFor(Sequences) {
returns("SELF")
doc { "Returns a sequence which performs the given [action] on each ${f.element} of the original sequence as they pass through it." }
sequenceClassification(intermediate, stateless)
body {
"""
return map {
action(it)
it
}
"""
}
}
}
val f_forEach = fn("forEach(action: (T) -> Unit)") {
includeDefault()
include(Maps, CharSequences, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc { "Performs the given [action] on each ${f.element}." }
specialFor(Iterables, Maps) { annotation("@kotlin.internal.HidesMembers") }
returns("Unit")
body {
"""
for (element in this) action(element)
"""
}
}
val f_forEachIndexed = fn("forEachIndexed(action: (index: Int, T) -> Unit)") {
includeDefault()
include(CharSequences, ArraysOfUnsigned)
} builder {
inline()
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc {
"""
Performs the given [action] on each ${f.element}, providing sequential index with the ${f.element}.
@param [action] function that takes the index of ${f.element.prefixWithArticle()} and the ${f.element} itself
and performs the desired action on the ${f.element}.
""" }
returns("Unit")
body {
fun checkOverflow(value: String) = if (f == Sequences || f == Iterables) "checkIndexOverflow($value)" else value
"""
var index = 0
for (item in this) action(${checkOverflow("index++")}, item)
"""
}
}
}