forked from JetBrains/kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Generators.kt
1276 lines (1147 loc) · 47.2 KB
/
Generators.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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 Generators : TemplateGroupBase() {
init {
defaultBuilder {
specialFor(ArraysOfUnsigned) {
sinceAtLeast("1.3")
annotation("@ExperimentalUnsignedTypes")
}
}
}
val f_plusElement = fn("plusElement(element: T)") {
include(Iterables, Collections, Sets, Sequences)
} builder {
inlineOnly()
doc { "Returns a list containing all elements of the original collection and then the given [element]." }
specialFor(Sets) {
doc {
"""
Returns a set containing all elements of the original set and then the given [element] if it isn't already in this set.
The returned set preserves the element iteration order of the original set.
"""
}
}
specialFor(Sequences) {
doc { "Returns a sequence containing all elements of the original sequence and then the given [element]." }
}
sequenceClassification(intermediate, stateless)
returns("List<T>")
specialFor(Sets, Sequences) { returns("SELF") }
body { "return plus(element)" }
}
val f_plus = fn("plus(element: T)") {
include(Iterables, Collections, Sets, Sequences)
} builder {
operator(true)
doc { "Returns a list containing all elements of the original collection and then the given [element]." }
sequenceClassification(intermediate, stateless)
returns("List<T>")
body {
"""
if (this is Collection) return this.plus(element)
val result = ArrayList<T>()
result.addAll(this)
result.add(element)
return result
"""
}
body(Collections) {
"""
val result = ArrayList<T>(size + 1)
result.addAll(this)
result.add(element)
return result
"""
}
specialFor(Sets, Sequences) { returns("SELF") }
specialFor(Sets) {
doc {
"""
Returns a set containing all elements of the original set and then the given [element] if it isn't already in this set.
The returned set preserves the element iteration order of the original set.
"""
}
body {
"""
val result = LinkedHashSet<T>(mapCapacity(size + 1))
result.addAll(this)
result.add(element)
return result
"""
}
}
specialFor(Sequences) {
doc { "Returns a sequence containing all elements of the original sequence and then the given [element]." }
body {
"""
return sequenceOf(this, sequenceOf(element)).flatten()
"""
}
}
}
val f_plus_iterable = fn("plus(elements: Iterable<T>)") {
include(Iterables, Collections, Sets, Sequences)
} builder {
operator(true)
doc { "Returns a list containing all elements of the original ${f.collection} and then all elements of the given [elements] collection." }
returns("List<T>")
specialFor(Sets, Sequences) { returns("SELF") }
body {
"""
if (this is Collection) return this.plus(elements)
val result = ArrayList<T>()
result.addAll(this)
result.addAll(elements)
return result
"""
}
body(Collections) {
"""
if (elements is Collection) {
val result = ArrayList<T>(this.size + elements.size)
result.addAll(this)
result.addAll(elements)
return result
} else {
val result = ArrayList<T>(this)
result.addAll(elements)
return result
}
"""
}
specialFor(Sets) {
doc {
"""
Returns a set containing all elements of the original set and the given [elements] collection,
which aren't already in this set.
The returned set preserves the element iteration order of the original set.
"""
}
body {
"""
val result = LinkedHashSet<T>(mapCapacity(elements.collectionSizeOrNull()?.let { this.size + it } ?: this.size * 2))
result.addAll(this)
result.addAll(elements)
return result
"""
}
}
specialFor(Sequences) {
doc {
"""
Returns a sequence containing all elements of original sequence and then all elements of the given [elements] collection.
Note that the source sequence and the collection being added are iterated only when an `iterator` is requested from
the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
"""
}
sequenceClassification(intermediate, stateless)
body {
"""
return sequenceOf(this, elements.asSequence()).flatten()
"""
}
}
}
val f_plus_array = fn("plus(elements: Array<out T>)") {
include(Iterables, Collections, Sets, Sequences)
} builder {
operator(true)
doc { "Returns a list containing all elements of the original collection and then all elements of the given [elements] array." }
returns("List<T>")
specialFor(Sets, Sequences) { returns("SELF") }
body {
"""
if (this is Collection) return this.plus(elements)
val result = ArrayList<T>()
result.addAll(this)
result.addAll(elements)
return result
"""
}
body(Collections) {
"""
val result = ArrayList<T>(this.size + elements.size)
result.addAll(this)
result.addAll(elements)
return result
"""
}
specialFor(Sets) {
doc {
"""
Returns a set containing all elements of the original set and the given [elements] array,
which aren't already in this set.
The returned set preserves the element iteration order of the original set.
"""
}
body {
"""
val result = LinkedHashSet<T>(mapCapacity(this.size + elements.size))
result.addAll(this)
result.addAll(elements)
return result
"""
}
}
specialFor(Sequences) {
doc {
"""
Returns a sequence containing all elements of original sequence and then all elements of the given [elements] array.
Note that the source sequence and the array being added are iterated only when an `iterator` is requested from
the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
"""
}
sequenceClassification(intermediate, stateless)
body {
"""
return this.plus(elements.asList())
"""
}
}
}
val f_plus_sequence = fn("plus(elements: Sequence<T>)") {
include(Iterables, Sets, Sequences, Collections)
} builder {
operator(true)
doc { "Returns a list containing all elements of the original collection and then all elements of the given [elements] sequence." }
returns("List<T>")
specialFor(Sets, Sequences) { returns("SELF") }
body {
"""
val result = ArrayList<T>()
result.addAll(this)
result.addAll(elements)
return result
"""
}
body(Collections) {
"""
val result = ArrayList<T>(this.size + 10)
result.addAll(this)
result.addAll(elements)
return result
"""
}
specialFor(Sets) {
doc {
"""
Returns a set containing all elements of the original set and the given [elements] sequence,
which aren't already in this set.
The returned set preserves the element iteration order of the original set.
"""
}
body {
"""
val result = LinkedHashSet<T>(mapCapacity(this.size * 2))
result.addAll(this)
result.addAll(elements)
return result
"""
}
}
specialFor(Sequences) {
doc {
"""
Returns a sequence containing all elements of original sequence and then all elements of the given [elements] sequence.
Note that the source sequence and the sequence being added are iterated only when an `iterator` is requested from
the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
"""
}
sequenceClassification(intermediate, stateless)
body {
"""
return sequenceOf(this, elements).flatten()
"""
}
}
}
val f_minusElement = fn("minusElement(element: T)") {
include(Iterables, Sets, Sequences)
} builder {
inline(Inline.Only)
doc { "Returns a list containing all elements of the original collection without the first occurrence of the given [element]." }
specialFor(Sets) {
doc {
"""
Returns a set containing all elements of the original set except the given [element].
The returned set preserves the element iteration order of the original set.
"""
}
}
specialFor(Sequences) {
doc { "Returns a sequence containing all elements of the original sequence without the first occurrence of the given [element]." }
sequenceClassification(intermediate, stateless)
}
returns("List<T>")
specialFor(Sets, Sequences) { returns("SELF") }
body { "return minus(element)" }
}
val f_minus = fn("minus(element: T)") {
include(Iterables, Sets, Sequences)
} builder {
operator(true)
doc { "Returns a list containing all elements of the original collection without the first occurrence of the given [element]." }
returns("List<T>")
body {
"""
val result = ArrayList<T>(collectionSizeOrDefault(10))
var removed = false
return this.filterTo(result) { if (!removed && it == element) { removed = true; false } else true }
"""
}
specialFor(Sets, Sequences) { returns("SELF") }
specialFor(Sets) {
doc {
"""
Returns a set containing all elements of the original set except the given [element].
The returned set preserves the element iteration order of the original set.
"""
}
body {
"""
val result = LinkedHashSet<T>(mapCapacity(size))
var removed = false
return this.filterTo(result) { if (!removed && it == element) { removed = true; false } else true }
"""
}
}
specialFor(Sequences) {
doc { "Returns a sequence containing all elements of the original sequence without the first occurrence of the given [element]." }
sequenceClassification(intermediate, stateless)
body {
"""
return object: Sequence<T> {
override fun iterator(): Iterator<T> {
var removed = false
return [email protected] { if (!removed && it == element) { removed = true; false } else true }.iterator()
}
}
"""
}
}
}
val f_minus_iterable = fn("minus(elements: Iterable<T>)") {
include(Iterables, Sets, Sequences)
} builder {
operator(true)
doc { "Returns a list containing all elements of the original collection except the elements contained in the given [elements] collection.\n" }
returns("List<T>")
specialFor(Sets, Sequences) { returns("SELF") }
body {
"""
val other = elements.convertToListIfNotCollection()
if (other.isEmpty())
return this.toList()
return this.filterNot { it in other }
"""
}
specialFor(Sets) {
doc {
"""
Returns a set containing all elements of the original set except the elements contained in the given [elements] collection.
The returned set preserves the element iteration order of the original set.
"""
}
body {
"""
val other = elements.convertToListIfNotCollection()
if (other.isEmpty())
return this.toSet()
if (other is Set)
return this.filterNotTo(LinkedHashSet<T>()) { it in other }
val result = LinkedHashSet<T>(this)
result.removeAll(other)
return result
"""
}
}
specialFor(Sequences) {
doc {
"""
Returns a sequence containing all elements of original sequence except the elements contained in the given [elements] collection.
Note that the source sequence and the collection being subtracted are iterated only when an `iterator` is requested from
the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
"""
}
sequenceClassification(intermediate, stateful)
body {
"""
return object: Sequence<T> {
override fun iterator(): Iterator<T> {
val other = elements.convertToListIfNotCollection()
if (other.isEmpty())
return [email protected]()
else
return [email protected] { it in other }.iterator()
}
}
"""
}
}
}
val f_minus_array = fn("minus(elements: Array<out T>)") {
include(Iterables, Sets, Sequences)
} builder {
operator(true)
doc { "Returns a list containing all elements of the original collection except the elements contained in the given [elements] array.\n" }
returns("List<T>")
specialFor(Sets, Sequences) { returns("SELF") }
body {
"""
if (elements.isEmpty()) return this.toList()
return this.filterNot { it in elements }
"""
}
specialFor(Sets) {
doc {
"""
Returns a set containing all elements of the original set except the elements contained in the given [elements] array.
The returned set preserves the element iteration order of the original set.
"""
}
body {
"""
val result = LinkedHashSet<T>(this)
result.removeAll(elements)
return result
"""
}
}
specialFor(Sequences) {
doc {
"""
Returns a sequence containing all elements of original sequence except the elements contained in the given [elements] array.
Note that the source sequence and the array being subtracted are iterated only when an `iterator` is requested from
the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
"""
}
sequenceClassification(intermediate, stateful)
body {
"""
if (elements.isEmpty()) return this
return object: Sequence<T> {
override fun iterator(): Iterator<T> {
return [email protected] { it in elements }.iterator()
}
}
"""
}
}
}
val f_minus_sequence = fn("minus(elements: Sequence<T>)") {
include(Iterables, Sets, Sequences)
} builder {
operator(true)
doc { "Returns a list containing all elements of the original collection except the elements contained in the given [elements] sequence.\n" }
returns("List<T>")
specialFor(Sets, Sequences) { returns("SELF") }
body {
"""
val other = elements.toList()
if (other.isEmpty())
return this.toList()
return this.filterNot { it in other }
"""
}
specialFor(Sets) {
doc {
"""
Returns a set containing all elements of the original set except the elements contained in the given [elements] sequence.
The returned set preserves the element iteration order of the original set.
"""
}
body {
"""
val result = LinkedHashSet<T>(this)
result.removeAll(elements)
return result
"""
}
}
specialFor(Sequences) {
doc {
"""
Returns a sequence containing all elements of original sequence except the elements contained in the given [elements] sequence.
Note that the source sequence and the sequence being subtracted are iterated only when an `iterator` is requested from
the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
The operation is _intermediate_ for this sequence and _terminal_ and _stateful_ for the [elements] sequence.
"""
}
body {
"""
return object: Sequence<T> {
override fun iterator(): Iterator<T> {
val other = elements.toList()
if (other.isEmpty())
return [email protected]()
else
return [email protected] { it in other }.iterator()
}
}
"""
}
}
}
val f_partition = fn("partition(predicate: (T) -> Boolean)") {
includeDefault()
include(CharSequences, Strings)
} builder {
inline()
doc {
"""
Splits the original ${f.collection} into pair of lists,
where *first* list contains elements for which [predicate] yielded `true`,
while *second* list contains elements for which [predicate] yielded `false`.
"""
}
sample(when (family) {
CharSequences, Strings -> "samples.text.Strings.partition"
ArraysOfObjects, ArraysOfPrimitives -> "samples.collections.Arrays.Transformations.partitionArrayOfPrimitives"
Sequences -> "samples.collections.Sequences.Transformations.partition"
else -> "samples.collections.Iterables.Operations.partition"
})
sequenceClassification(terminal)
returns("Pair<List<T>, List<T>>")
body {
"""
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
"""
}
specialFor(CharSequences, Strings) {
doc {
"""
Splits the original ${f.collection} into pair of ${f.collection}s,
where *first* ${f.collection} contains characters for which [predicate] yielded `true`,
while *second* ${f.collection} contains characters for which [predicate] yielded `false`.
"""
}
returns("Pair<SELF, SELF>")
}
body(CharSequences, Strings) {
val toString = if (f == Strings) ".toString()" else ""
"""
val first = StringBuilder()
val second = StringBuilder()
for (element in this) {
if (predicate(element)) {
first.append(element)
} else {
second.append(element)
}
}
return Pair(first$toString, second$toString)
"""
}
}
val f_windowed_transform = fn("windowed(size: Int, step: Int = 1, partialWindows: Boolean = false, transform: (List<T>) -> R)") {
include(Iterables, Sequences, CharSequences)
} builder {
since("1.2")
doc {
"""
Returns a ${f.mapResult} of results of applying the given [transform] function to
an each ${f.viewResult} representing a view over the window of the given [size]
sliding along this ${f.collection} with the given [step].
Note that the ${f.viewResult} passed to the [transform] function is ephemeral and is valid only inside that function.
You should not store it or allow it to escape in some way, unless you made a snapshot of it.
Several last ${f.viewResult.pluralize()} may have fewer ${f.element.pluralize()} than the given [size].
Both [size] and [step] must be positive and can be greater than the number of elements in this ${f.collection}.
@param size the number of elements to take in each window
@param step the number of elements to move the window forward by on an each step, by default 1
@param partialWindows controls whether or not to keep partial windows in the end if any,
by default `false` which means partial windows won't be preserved
"""
}
sample("samples.collections.Sequences.Transformations.averageWindows")
typeParam("R")
returns("List<R>")
body {
"""
checkWindowSizeStep(size, step)
if (this is RandomAccess && this is List) {
val thisSize = this.size
val resultCapacity = thisSize / step + if (thisSize % step == 0) 0 else 1
val result = ArrayList<R>(resultCapacity)
val window = MovingSubList(this)
var index = 0
while (index in 0 until thisSize) {
val windowSize = size.coerceAtMost(thisSize - index)
if (!partialWindows && windowSize < size) break
window.move(index, index + windowSize)
result.add(transform(window))
index += step
}
return result
}
val result = ArrayList<R>()
windowedIterator(iterator(), size, step, partialWindows, reuseBuffer = true).forEach {
result.add(transform(it))
}
return result
"""
}
specialFor(CharSequences) {
signature("windowed(size: Int, step: Int = 1, partialWindows: Boolean = false, transform: (CharSequence) -> R)")
}
body(CharSequences) {
"""
checkWindowSizeStep(size, step)
val thisSize = this.length
val resultCapacity = thisSize / step + if (thisSize % step == 0) 0 else 1
val result = ArrayList<R>(resultCapacity)
var index = 0
while (index in 0 until thisSize) {
val end = index + size
val coercedEnd = if (end < 0 || end > thisSize) { if (partialWindows) thisSize else break } else end
result.add(transform(subSequence(index, coercedEnd)))
index += step
}
return result
"""
}
specialFor(Sequences) { returns("Sequence<R>") }
body(Sequences) {
"""
return windowedSequence(size, step, partialWindows, reuseBuffer = true).map(transform)
"""
}
}
val f_windowed = fn("windowed(size: Int, step: Int = 1, partialWindows: Boolean = false)") {
include(Iterables, Sequences, CharSequences)
} builder {
since("1.2")
specialFor(Iterables) { returns("List<List<T>>") }
specialFor(Sequences) { returns("Sequence<List<T>>") }
specialFor(CharSequences) { returns("List<String>") }
doc {
"""
Returns a ${f.mapResult} of snapshots of the window of the given [size]
sliding along this ${f.collection} with the given [step], where each
snapshot is ${f.snapshotResult.prefixWithArticle()}.
Several last ${f.snapshotResult.pluralize()} may have fewer ${f.element.pluralize()} than the given [size].
Both [size] and [step] must be positive and can be greater than the number of elements in this ${f.collection}.
@param size the number of elements to take in each window
@param step the number of elements to move the window forward by on an each step, by default 1
@param partialWindows controls whether or not to keep partial windows in the end if any,
by default `false` which means partial windows won't be preserved
"""
}
sample("samples.collections.Sequences.Transformations.takeWindows")
body {
"""
checkWindowSizeStep(size, step)
if (this is RandomAccess && this is List) {
val thisSize = this.size
val resultCapacity = thisSize / step + if (thisSize % step == 0) 0 else 1
val result = ArrayList<List<T>>(resultCapacity)
var index = 0
while (index in 0 until thisSize) {
val windowSize = size.coerceAtMost(thisSize - index)
if (windowSize < size && !partialWindows) break
result.add(List(windowSize) { this[it + index] })
index += step
}
return result
}
val result = ArrayList<List<T>>()
windowedIterator(iterator(), size, step, partialWindows, reuseBuffer = false).forEach {
result.add(it)
}
return result
"""
}
body(CharSequences) { "return windowed(size, step, partialWindows) { it.toString() }" }
body(Sequences) {
"""
return windowedSequence(size, step, partialWindows, reuseBuffer = false)
"""
}
}
val f_windowedSequence_transform = fn("windowedSequence(size: Int, step: Int = 1, partialWindows: Boolean = false, transform: (CharSequence) -> R)") {
include(CharSequences)
} builder {
since("1.2")
doc {
"""
Returns a sequence of results of applying the given [transform] function to
an each ${f.viewResult} representing a view over the window of the given [size]
sliding along this ${f.collection} with the given [step].
Note that the ${f.viewResult} passed to the [transform] function is ephemeral and is valid only inside that function.
You should not store it or allow it to escape in some way, unless you made a snapshot of it.
Several last ${f.viewResult.pluralize()} may have fewer ${f.element.pluralize()} than the given [size].
Both [size] and [step] must be positive and can be greater than the number of elements in this ${f.collection}.
@param size the number of elements to take in each window
@param step the number of elements to move the window forward by on an each step, by default 1
@param partialWindows controls whether or not to keep partial windows in the end if any,
by default `false` which means partial windows won't be preserved
"""
}
sample("samples.collections.Sequences.Transformations.averageWindows")
typeParam("R")
returns("Sequence<R>")
body {
"""
checkWindowSizeStep(size, step)
val windows = (if (partialWindows) indices else 0 until length - size + 1) step step
return windows.asSequence().map { index ->
val end = index + size
val coercedEnd = if (end < 0 || end > length) length else end
transform(subSequence(index, coercedEnd))
}
"""
}
}
val f_windowedSequence = fn("windowedSequence(size: Int, step: Int = 1, partialWindows: Boolean = false)") {
include(CharSequences)
} builder {
since("1.2")
doc {
"""
Returns a sequence of snapshots of the window of the given [size]
sliding along this ${f.collection} with the given [step], where each
snapshot is ${f.snapshotResult.prefixWithArticle()}.
Several last ${f.snapshotResult.pluralize()} may have fewer ${f.element.pluralize()} than the given [size].
Both [size] and [step] must be positive and can be greater than the number of elements in this ${f.collection}.
@param size the number of elements to take in each window
@param step the number of elements to move the window forward by on an each step, by default 1
@param partialWindows controls whether or not to keep partial windows in the end if any,
by default `false` which means partial windows won't be preserved
"""
}
sample("samples.collections.Sequences.Transformations.takeWindows")
returns("Sequence<String>")
body(CharSequences) { "return windowedSequence(size, step, partialWindows) { it.toString() }" }
}
val f_chunked_transform = fn("chunked(size: Int, transform: (List<T>) -> R)") {
include(Iterables, Sequences, CharSequences)
} builder {
since("1.2")
doc {
"""
Splits this ${f.collection} into several ${f.viewResult.pluralize()} each not exceeding the given [size]
and applies the given [transform] function to an each.
@return ${f.mapResult} of results of the [transform] applied to an each ${f.viewResult}.
Note that the ${f.viewResult} passed to the [transform] function is ephemeral and is valid only inside that function.
You should not store it or allow it to escape in some way, unless you made a snapshot of it.
The last ${f.viewResult} may have fewer ${f.element.pluralize()} than the given [size].
@param size the number of elements to take in each ${f.viewResult}, must be positive and can be greater than the number of elements in this ${f.collection}.
"""
}
sample("samples.text.Strings.chunkedTransform")
typeParam("R")
returns("List<R>")
specialFor(CharSequences) {
signature("chunked(size: Int, transform: (CharSequence) -> R)")
}
sequenceClassification(intermediate, stateful)
specialFor(Sequences) { returns("Sequence<R>") }
body { "return windowed(size, size, partialWindows = true, transform = transform)" }
}
val f_chunked = fn("chunked(size: Int)") {
include(Iterables, Sequences, CharSequences)
} builder {
since("1.2")
doc {
"""
Splits this ${f.collection} into a ${f.mapResult} of ${f.snapshotResult.pluralize()} each not exceeding the given [size].
The last ${f.snapshotResult} in the resulting ${f.mapResult} may have fewer ${f.element.pluralize()} than the given [size].
@param size the number of elements to take in each ${f.snapshotResult}, must be positive and can be greater than the number of elements in this ${f.collection}.
"""
}
specialFor(Iterables, Sequences) { sample("samples.collections.Collections.Transformations.chunked") }
specialFor(CharSequences) { sample("samples.text.Strings.chunked") }
specialFor(Iterables) { returns("List<List<T>>") }
specialFor(Sequences) { returns("Sequence<List<T>>") }
specialFor(CharSequences) { returns("List<String>") }
sequenceClassification(intermediate, stateful)
body { "return windowed(size, size, partialWindows = true)" }
}
val f_chunkedSequence_transform = fn("chunkedSequence(size: Int, transform: (CharSequence) -> R)") {
include(CharSequences)
} builder {
since("1.2")
doc {
"""
Splits this ${f.collection} into several ${f.viewResult.pluralize()} each not exceeding the given [size]
and applies the given [transform] function to an each.
@return sequence of results of the [transform] applied to an each ${f.viewResult}.
Note that the ${f.viewResult} passed to the [transform] function is ephemeral and is valid only inside that function.
You should not store it or allow it to escape in some way, unless you made a snapshot of it.
The last ${f.viewResult} may have fewer ${f.element.pluralize()} than the given [size].
@param size the number of elements to take in each ${f.viewResult}, must be positive and can be greater than the number of elements in this ${f.collection}.
"""
}
sample("samples.text.Strings.chunkedTransformToSequence")
typeParam("R")
returns("Sequence<R>")
body {
"""
return windowedSequence(size, size, partialWindows = true, transform = transform)
"""
}
}
val f_chunkedSequence = fn("chunkedSequence(size: Int)") {
include(CharSequences)
} builder {
since("1.2")
doc {
"""
Splits this ${f.collection} into a sequence of ${f.snapshotResult.pluralize()} each not exceeding the given [size].
The last ${f.snapshotResult} in the resulting sequence may have fewer ${f.element.pluralize()} than the given [size].
@param size the number of elements to take in each ${f.snapshotResult}, must be positive and can be greater than the number of elements in this ${f.collection}.
"""
}
sample("samples.collections.Collections.Transformations.chunked")
returns("Sequence<String>")
body(CharSequences) { "return chunkedSequence(size) { it.toString() }" }
}
val f_zipWithNext_transform = fn("zipWithNext(transform: (a: T, b: T) -> R)") {
include(Iterables, Sequences, CharSequences)
} builder {
since("1.2")
typeParam("R")
doc {
"""
Returns a ${f.mapResult} containing the results of applying the given [transform] function
to an each pair of two adjacent ${f.element.pluralize()} in this ${f.collection}.
The returned ${f.mapResult} is empty if this ${f.collection} contains less than two ${f.element.pluralize()}.
"""
}
sample("samples.collections.Collections.Transformations.zipWithNextToFindDeltas")
returns("List<R>")
inline()
body {
"""
val iterator = iterator()
if (!iterator.hasNext()) return emptyList()
val result = mutableListOf<R>()
var current = iterator.next()
while (iterator.hasNext()) {
val next = iterator.next()
result.add(transform(current, next))
current = next
}
return result
"""
}
body(CharSequences) {
"""
val size = ${f.code.size} - 1
if (size < 1) return emptyList()
val result = ArrayList<R>(size)
for (index in 0 until size) {
result.add(transform(this[index], this[index + 1]))
}
return result
"""
}
sequenceClassification(intermediate, stateless)
specialFor(Sequences) {
inline(Inline.No)
returns("Sequence<R>")
}
body(Sequences) {
"""
return sequence result@ {
val iterator = iterator()
if (!iterator.hasNext()) return@result
var current = iterator.next()
while (iterator.hasNext()) {
val next = iterator.next()
yield(transform(current, next))
current = next
}
}
"""
}
}
val f_zipWithNext = fn("zipWithNext()") {
include(Iterables, Sequences, CharSequences)
} builder {
since("1.2")
returns("List<Pair<T, T>>")
doc {
"""
Returns a ${f.mapResult} of pairs of each two adjacent ${f.element.pluralize()} in this ${f.collection}.
The returned ${f.mapResult} is empty if this ${f.collection} contains less than two ${f.element.pluralize()}.
"""
}
sample("samples.collections.Collections.Transformations.zipWithNext")
sequenceClassification(intermediate, stateless)
specialFor(Sequences) { returns("Sequence<Pair<T, T>>") }
body {
"return zipWithNext { a, b -> a to b }"
}
}