-
Notifications
You must be signed in to change notification settings - Fork 15
/
List.x
1480 lines (1322 loc) · 49.4 KB
/
List.x
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
/**
* The `List` interface represents a collection of values stored in a specific order. An example of
* a list is the linked list data structure, in which each item in the list points to the next item.
*
* While `List` supports indexed access, it does not guarantee that the access occurs in less than
* `O(N)` time. An implementation of List that provides `O(1)` access time is said to be _indexed_;
* all other implementations of List are said to _emulate_ indexing for those methods taking an
* index as an argument. For all indexed access, the index is `0`-based.
*/
interface List<Element>
extends Collection<Element>
extends UniformIndexed<Int, Element>
extends Sliceable<Int> {
// ----- metadata ------------------------------------------------------------------------------
@Override
conditional Orderer? ordered() {
// there is an order to a list, but (unless otherwise specified) not based on an Orderer
return True, Null;
}
/**
* Metadata: Does this `List` provide efficient O(1) access times when using the index-based
* methods to access values from the List?
*/
@RO Boolean indexed.get() {
return True;
}
// ----- read operations -----------------------------------------------------------------------
@Override
Iterator<Element> iterator() {
// implementations that are not indexed should provide a more efficient implementation
return new Iterator() {
private Int i = 0;
@Override
conditional Element next() {
if (i < this.List.size) {
return True, this.List[i++];
}
return False;
}
};
}
@Override
Boolean contains(Element value) {
if (Orderer? order := ordered(), order != Null) {
// binary search
Int lo = 0;
Int hi = size - 1;
while (lo <= hi) {
Int mid = (lo + hi) >> 1;
Element cur = this[mid];
switch (order(value, cur)) {
case Lesser:
hi = mid - 1;
break;
case Equal:
return True;
case Greater:
lo = mid + 1;
break;
}
}
return False;
}
if (indexed, Int size := knownSize()) {
for (Int i = 0; i < size; ++i) {
if (this[i] == value) {
return True;
}
}
return False;
}
return super(value);
}
/**
* Obtain the first element in the list.
*
* @return True iff the list is not empty
* @return the first element in the list
*/
conditional Element first() {
if (empty) {
return False;
}
return True, this[0];
}
/**
* Obtain the last element in the list.
*
* @return True iff the list is not empty
* @return the last element in the list
*/
conditional Element last() {
if (empty) {
return False;
}
if (indexed, Int size := knownSize()) {
return True, this[size-1];
}
Iterator<Element> iter = iterator();
assert Element value := iter.next();
while (value := iter.next()) {
}
return True, value;
}
/**
* Determine if `this` list _starts-with_ `that` list. A list `this` of at least `n`
* elements "starts-with" another list `that` of exactly `n` elements iff, for each index
* `0..<n`, the element at the index in `this` list is equal to the element at the same
* index in `that` list.
*
* @param that a list to look for at the beginning of this list
*
* @return True iff this list starts-with that list
*/
Boolean startsWith(List! that) {
if (Int thisSize := this.knownSize(),
Int thatSize := that.knownSize()) {
if (thatSize == 0) {
return True;
}
if (thisSize < thatSize) {
return False;
}
if (this.indexed && that.indexed) {
for (Int i : 0 ..< thatSize) {
if (this[i] != that[i]) {
return False;
}
}
return True;
}
}
// fall-back: use iterators to compare the items in the two lists
using (Iterator<Element> thisIter = this.iterator(),
Iterator<Element> thatIter = that.iterator()) {
while (Element thatElem := thatIter.next()) {
if (Element thisElem := thisIter.next()) {
continue;
} else {
return False;
}
}
}
return True;
}
/**
* Determine if `this` list _ends-with_ `that` list. A list `this` of `m` elements
* "ends-with" another list `that` of `n` elements iff `n <= m` and, for each index `i`
* in the range `0..<n`, the element at the index `m-n+i` in `this` list is equal to the
* element at index `i` in `that` list.
*
* @param that a list to look for at the end of this list
*
* @return True iff this list end-with that list
*/
Boolean endsWith(List! that) {
Int thatSize = that.size;
if (thatSize == 0) {
return True;
}
Int thisSize = this.size;
if (thisSize < thatSize) {
return False;
}
Int offset = thisSize - thatSize;
if (this.indexed && that.indexed) {
for (Int i : 0 ..< thatSize) {
if (this[offset+i] != that[i]) {
return False;
}
}
return True;
}
Iterator<Element> thisIter = this.iterator();
Iterator<Element> thatIter = that.iterator();
for (Int i : 0 ..< offset) {
assert thisIter.next();
}
while (Element thatVal := thatIter.next()) {
assert Element thisVal := thisIter.next();
if (thisVal != thatVal) {
return False;
}
}
assert !thisIter.next();
return True;
}
/**
* Look for the specified `value` starting at the specified index.
*
* @param value the value to search for
* @param startAt the first index to search from (optional)
*
* @return True iff this list contains the `value`, at or after the `startAt` index
* @return (conditional) the index at which the specified value was found
*/
conditional Int indexOf(Element value, Int startAt = 0) {
if (Orderer? order := ordered(), order != Null) {
if (Int index := binarySearch(value, order)) {
while (index > startAt && this[index-1] == value) {
--index;
}
return True, index;
}
return False;
}
if (indexed, Int size := knownSize()) {
for (Int i = startAt.notLessThan(0); i < size; ++i) {
if (this[i] == value) {
return True, i;
}
}
return False;
}
Loop: for (Element e : iterator()) {
if (Loop.count >= startAt && e == value) {
return True, Loop.count;
}
}
return False;
}
/**
* Search the list using the supplied function.
*
* @param match the match function to use
* @param startAt the first index to search from (optional)
*
* @return True iff a match was found
* @return the index at which the specified value was found
*/
conditional Int indexOf(function Boolean(Element) match, Int startAt = 0) {
if (indexed, Int size := knownSize()) {
for (Int i = startAt.notLessThan(0); i < size; ++i) {
if (match(this[i])) {
return True, i;
}
}
return False;
}
Loop: for (Element e : iterator()) {
if (Loop.count >= startAt && match(e)) {
return True, Loop.count;
}
}
return False;
}
/**
* Determine if `this` list _contains_ `that` list, and at what index `that` list
* first occurs.
*
* @param that a list to look for within this list
* @param startAt (optional) the first index to search from
*
* @return True iff this list contains that list, at or after the `startAt` index
* @return (conditional) the index at which the specified list of values was found
*/
conditional Int indexOf(List! that, Int startAt = 0) {
Int length = that.size;
startAt = startAt.notLessThan(0);
if (length == 0) {
return startAt > size ? False : (True, startAt);
}
Element firstMatch = that[0];
Next: for (Int offset = startAt, Int stopAt = this.size - length; offset <= stopAt; ++offset) {
if (this[offset] == firstMatch) {
for (Int i = 1; i < length; ++i) {
if (this[offset + i] != that[i]) {
continue Next;
}
}
return True, offset;
}
}
return False;
}
/**
* Look for the specified `value` starting at the specified index and searching backwards.
*
* @param value the value to search for
* @param startAt the index to start searching backwards from (optional)
*
* @return True iff this list contains the `value`, at or before the `startAt` index
* @return (conditional) the index at which the specified value was found
*/
conditional Int lastIndexOf(Element value, Int startAt = MaxValue) {
if (Orderer? order := ordered(), order != Null) {
if (Int index := binarySearch(value, order)) {
Int stop = startAt.notGreaterThan(size-1);
while (index < stop && this[index+1] == value) {
++index;
}
return True, index;
}
return False;
}
if (indexed) {
for (Int i = startAt.notGreaterThan(size-1); i >= 0; --i) {
if (this[i] == value) {
return True, i;
}
}
return False;
}
Int last = -1;
Loop: for (Element e : iterator()) {
if (Loop.count > startAt) {
break;
}
if (e == value) {
last = Loop.count;
}
}
return last >= 0
? (True, last)
: False;
}
/**
* Search backwards the list using the supplied function.
*
* @param match the match function to use
* @param startAt (optional) the index to start searching backwards from
*
* @return True iff a match was found
* @return the index at which the specified value was found
*/
conditional Int lastIndexOf(function Boolean(Element) match, Int startAt = 0) {
if (indexed) {
for (Int i = startAt.notGreaterThan(size-1); i >= 0; --i) {
if (match(this[i])) {
return True, i;
}
}
return False;
}
Int last = -1;
Loop: for (Element e : iterator()) {
if (Loop.count > startAt) {
break;
}
if (match(e)) {
last = Loop.count;
}
}
return last >= 0
? (True, last)
: False;
}
/**
* Determine if `this` list _contains_ `that` list, and at what index `that` list
* last occurs.
*
* @param that a list to look for within this list
* @param startAt (optional) the index to start searching backwards from
*
* @return True iff this list contains that list, at or before the `startAt` index
* @return (conditional) the index at which the specified list of values was found
*/
conditional Int lastIndexOf(List! that, Int startAt = MaxValue) {
Int length = that.size;
startAt = startAt.notGreaterThan(this.size-length);
if (length == 0) {
return startAt < 0 ? False : (True, startAt);
}
Element firstMatch = that[0];
Next: for (Int offset = startAt; offset >= 0; --offset) {
if (this[offset] == firstMatch) {
for (Int i = 1; i < length; ++i) {
if (this[offset + i] != that[i]) {
continue Next;
}
}
return True, offset;
}
}
return False;
}
/**
* Look for the specified `value` in the list, with the assumption that the list is ordered.
*
* @param value the value to search for
* @param compare the ordering comparison function to use
*
* @return True iff this list contains the `value`
* @return the index at which the specified value was found, or the insertion point if the
* value was not found
*/
(Boolean found, Int index) binarySearch(Element value, Orderer? compare=Null) {
if (compare == Null) {
assert compare := Element.ordered();
}
return binarySearch(compare(value, _));
}
/**
* Binary search the list using the supplied function.
*
* @param compare the ordering comparison function to use
*
* @return True iff a match was found
* @return the index at which the specified value was found, or the insertion point if the
* value was not found
*/
(Boolean found, Int index) binarySearch(function Ordered(Element) order) {
switch (Int size = this.size) {
case 0:
return False, 0;
case 1:
return switch (order(this[0])) {
case Lesser: (False, 0);
case Equal: (True, 0);
case Greater: (False, 1);
};
case 2..4:
// linear probe assumed to be faster than binary search for a small list
Each: for (Element each : this) {
switch (order(each)) {
case Lesser:
return (False, Each.count);
case Equal:
return (True, Each.count);
}
}
return False, size;
default:
Int first = 0;
Int last = size - 1;
do {
Int midpoint = (first + last) >> 1;
switch (order(this[midpoint])) {
case Lesser:
last = midpoint - 1;
break;
case Equal:
return True, midpoint;
case Greater:
first = midpoint + 1;
break;
}
} while (first <= last);
return False, first;
}
}
/**
* Evaluate the contents of this `Collection` using the provided criteria, and produce a
* resulting `Collection` that contains only the elements that match.
*
* @param match a function that evaluates an element of the `Collection` for inclusion
* @param dest an optional `Collection` to collect the results in; pass `this` collection to
* filter out the values "in place"
*
* @return the resulting `Collection` containing the elements that matched the criteria
*/
List! filterIndexed(function Boolean(Element, Int) match,
List? dest = Null) {
if (&dest == &this) {
Cursor cur = cursor();
Int index = 0;
while (cur.exists) {
// note that since this is occurring "in place", the cursor index will not advance
// after a node is deleted, so the original index is simulated with the counter
if (match(cur.value, index++)) {
cur.advance();
} else {
cur.delete();
}
}
return this;
}
dest ?:= new Element[];
Loop: for (Element e : this) {
if (match(e, Loop.count)) {
dest += e;
}
}
return dest;
}
/**
* Build a `Collection` that has one value "mapped from" each value in this `Collection`, using
* the provided function.
*
* @param transform a function that creates the "mapped" element from an element in this
* `Collection`
* @param dest an optional `Collection` to collect the results in; pass `this` collection
* to map the values "in place"
*
* @return the resulting `Collection` containing the elements that matched the criteria
*/
<Result> List!<Result> mapIndexed(function Result(Element, Int) transform,
List!<Result>? dest = Null) {
// in place
if (&dest == &this) {
assert inPlace;
Cursor cur = cursor(0);
while (cur.exists) {
cur.value = transform(cur.value, cur.index).as(Element);
cur.advance();
}
assert dest != Null;
return dest;
}
dest ?:= new Result[];
Loop: for (Element e : this) {
dest.add(transform(e, Loop.count));
}
return dest;
}
/**
* Reduce this Collection of elements to a result value using the provided function. This
* operation is also called a _folding_ operation.
*
* @param initial the initial value to start accumulating from
* @param accumulate the function that will be used to accumulate elements into a result
*
* @return the result of the reduction
*/
<Result> Result reduceIndexed(Result initial,
function Result(Result, Element, Int) accumulate) {
Result result = initial;
Loop: for (Element e : this) {
result = accumulate(result, e, Loop.count);
}
return result;
}
/**
* Chunk up this List into certain sized chunks, and evaluate each chunk, collecting the
* results.
*
* @param size the size of the window
* @param process the function to apply to each chunk
*
* @return the list of results from the `process` function
*/
<Result> List!<Result> chunked(Int size,
function Result(List<Element>) process) {
assert:arg size > 0;
Result[] results = new Result[];
for (Int i = 0, Int thisSize = this.size; i < thisSize; i += size) {
results.add(process(this[i ..< (i+size).notGreaterThan(thisSize)]));
}
return results;
}
/**
* Slide a window over this List, evaluating the contents of the window as it moves using the
* provided `process` function.
*
* @param size the size of the window
* @param process the function to apply to each window
* @param step the amount to move the window on each iteration
* @param partial False indicates that only full-sized windows will be evaluated; True
* allows partial windows to be evaluated
*
* @return the list of results from the `process` function on each window
*/
<Result> List!<Result> windowed(Int size,
function Result(List<Element>) process,
Int step = 1,
Boolean partial = False) {
assert:arg size > 0;
Result[] results = new Result[];
Int thisSize = this.size;
Int stop = thisSize - (partial ? 1 : size);
for (Int i = 0; i <= stop; i += step) {
results.add(process(this[i ..< (i+size).notGreaterThan(thisSize)]));
}
return results;
}
/**
* Sort the contents of this list in the order specified by the optional [Type.Orderer].
*
* @param order (optional) the Orderer to use to sort the list, defaulting to using the
* "natural" sort order of the Element type
* @param collector (optional) an [Aggregator] to use to collect the results; if specified,
* the value of `inPlace` argument is ignored
* @param inPlace (optional) pass `True` to allow the List to sort itself "in place", if the
* List is able to do so
*
* @return the resultant list, which is the same as `this` for a mutable list
*
* @throws ReadOnly if the collector is not specified, the value of `inPlace` argument is `True`,
* but the List is not mutable
*/
@Override
<Result extends List!> Result sorted(Orderer? order = Null,
Aggregator<Element, Result>? collector = Null,
Boolean inPlace = False) {
if (collector != Null) {
return super(order, collector);
}
Int size = this.size;
if (size <= 1 && (inPlace || !this.inPlace)) {
// nothing to sort
return this.as(Result);
}
if (order != Null, Orderer? prev := ordered(), prev? == order) {
// already in the right order
return (inPlace
? this
: this[0 ..< size]).as(Result);
}
if (inPlace && !this.inPlace) {
throw new ReadOnly();
}
return (inPlace
? sort(order)
: super(order)).as(Result);
}
/**
* Obtain a new List that represents the reverse order of this List.
*
* If a stable snapshot is required, then the caller must [reify](Collection.reify()] the
* returned `List`.
*
* @param inPlace pass `True` to allow the List to reverse its order in-place, without creating
* a new List; note that the List implementation may still choose to create a
* new List to satisfy the request, so this parameter is only a suggestion
*
* @return a List that is in the reverse order as this List
*/
List! reversed(Boolean inPlace = False) {
if (indexed, Int size := knownSize()) {
if (size <= 1 && (inPlace || !this.inPlace)) {
return this;
}
if (inPlace && this.inPlace) {
// swap the elements in-place to reverse the list
for (Int i = 0, Int swap = size >> 1; i < swap; ++i) {
Element e1 = this[i];
Element e2 = this[size - i - 1];
this[size - i - 1] = e1;
this[i] = e2;
}
return this;
}
return this[size >.. 0];
}
return new Array<Element>(Mutable, this).reversed(True);
}
/**
* Obtain a new List that represents a randomized order of this List.
*
* @param inPlace pass `True` to allow the List to shuffle its order in-place, without creating
* a new List; note that the List implementation may still choose to create a
* new to satisfy the request, so this parameter is only used as a suggestion
*
* @return a List that contains this List's contents, but in a randomly-shuffled order
*/
List! shuffled(Boolean inPlace = False) {
if (Int size := knownSize()) {
if (size <= 1 && (inPlace || !this.inPlace)) {
return this;
}
if (inPlace && this.inPlace && indexed) {
@Inject Random random;
Loop: for (Element e : this) {
Int swapFrom = random.int(size);
if (Loop.count != swapFrom) {
Element swapValue = this[swapFrom];
this[swapFrom ] = e;
this[Loop.count] = swapValue;
}
}
return this;
}
}
return new Array<Element>(Mutable, this).shuffled(True);
}
@Override
List reify() {
// this method must be overridden by any implementing Collection that may return a view of
// itself as a Collection, such that mutations to one might be visible from the other
return this;
}
// ----- write operations ----------------------------------------------------------------------
@Override
@Op("-") List remove(Element value) {
if (Int index := indexOf(value)) {
return delete(index);
}
return this;
}
@Override
conditional List removeIfPresent(Element value) {
if (Int index := indexOf(value)) {
return True, delete(index);
}
return False;
}
@Override
(List, Int) removeAll(function Boolean (Element) shouldRemove) {
List<Element> result = this;
Int count = 0;
if (inPlace && !indexed) {
Cursor cur = cursor(0);
while (cur.exists) {
if (shouldRemove(cur.value)) {
cur.delete();
++count;
} else {
cur.advance();
}
}
} else {
Int index = 0;
Int size = this.size;
while (index < size) {
if (shouldRemove(result[index])) {
result = result.delete(index);
--size;
++count;
} else {
++index;
}
}
}
return result, count;
}
/**
* Replace the existing value in the List at the specified index with the specified value.
*
* @param index the index at which to store the specified value, which must be between `0`
* (inclusive) and `size` (exclusive)
* @param value the value to store
*
* @return the resultant list, which is the same as `this` for a mutable list
*
* @throws OutOfBounds if the specified index is outside of range `0` (inclusive) to
* `size` (inclusive)
*/
List replace(Int index, Element value) {
if (inPlace && !this.is(immutable)) {
this[index] = value;
return this;
}
throw new ReadOnly($"{this:class} is immutable or does not support replace()");
}
/**
* Replace existing values in the List with the provided values, starting at the specified
* index.
*
* @param index the index at which to store the specified value, which must be between `0`
* (inclusive) and `size` (exclusive)
* @param values the values to store
*
* @return the resultant list, which is the same as `this` for a mutable list
*
* @throws OutOfBounds if the specified index is outside of range `0` (inclusive) to
* `size` (inclusive), or if the specified index plus the size of the
* provided Iterable is greater than the size of this array
*/
List replaceAll(Int index, Iterable<Element> values) {
// this implementation should be overridden by any non-mutable implementation of List, and
// by any implementation that is able to replace multiple elements efficiently
Int i = index;
List result = this;
for (Element value : values) {
result = result.replace(i++, value);
}
return result;
}
/**
* Insert the specified value into the List at the specified index, shifting the contents of the
* entire remainder of the list as a result. If the index is beyond the end of the list, this
* operation has the same effect as calling [add].
*
* Warning: This can be an incredibly expensive operation if the data structure is not
* explicitly intended to support efficient insertion.
*
* @param index the index at which to insert, which must be between `0` (inclusive) and
* `size` (inclusive)
* @param value the value to insert
*
* @return the resultant list, which is the same as `this` for a mutable list
*
* @throws OutOfBounds if the specified index is outside of range `0` (inclusive) to
* `size` (inclusive)
*/
List insert(Int index, Element value) {
throw new ReadOnly($"{this:class} does not support insert()");
}
/**
* Insert the specified values into the List at the specified index, shifting the contents of
* the entire remainder of the list as a result. If the index is beyond the end of the list,
* this operation has the same effect as calling [addAll].
*
* Warning: This can be an incredibly expensive operation if the data structure is not
* explicitly intended to support efficient insertion.
*
* @param index the index at which to insert, which must be between `0` (inclusive) and
* `size` (inclusive)
* @param values the values to insert
*
* @return the resultant list, which is the same as `this` for a mutable list
*
* @throws OutOfBounds if the specified index is outside of range `0` (inclusive) to
* `size` (inclusive)
*/
List insertAll(Int index, Iterable<Element> values) {
// this implementation should be overridden by any non-mutable implementation of List, and
// by any implementation that is able to insert multiple elements efficiently
Int i = index;
List result = this;
for (Element value : values) {
result = result.insert(i++, value);
}
return result;
}
/**
* Delete the element at the specified index, shifting the contents of the entire remainder of
* the list as a result.
*
* Warning: This can be an incredibly expensive operation if the data structure is not
* explicitly intended to support efficient deletion.
*
* @param index the index of the element to delete, which must be between `0` (inclusive)
* and `size` (exclusive)
*
* @return the resultant list, which is the same as `this` for a mutable list
*
* @throws OutOfBounds if the specified index is outside of range `0` (inclusive) to
* `size` (exclusive)
*/
List delete(Int index) {
throw new ReadOnly($"{this:class} does not support delete()");
}
/**
* Delete the elements within the specified range, shifting the contents of the entire remainder
* of the list as a result.
*
* Warning: This can be an incredibly expensive operation if the data structure is not
* explicitly intended to support efficient deletion.
*
* @param indexes the interval of indexes of the elements to delete, which must be between `0`
* (inclusive) and `size` (exclusive)
*
* @return the resultant list, which is the same as `this` for a mutable list
*
* @throws OutOfBounds if any of the specified indexes is outside of range `0` (inclusive) to
* `size` (exclusive)
*/
List deleteAll(Interval<Int> indexes) {
// this implementation should be overridden by any non-mutable implementation of List, and
// by any implementation that is able to delete multiple elements efficiently
List result = this;
for (Int index = indexes.effectiveLowerBound, Int count = indexes.size; count-- > 0; ) {
result = result.delete(index);
}
return result;
}
// ----- List Cursor ---------------------------------------------------------------------------
/**
* Obtain a list cursor that is located at the specified index.
*
* @param index the index within the list to position the cursor; (optional, defaults to the
* beginning of the list)
*
* @return a new Cursor positioned at the specified index in the List
*
* @throws OutOfBounds if the specified index is outside of range `0` (inclusive) to
* `size` (inclusive)
*/
Cursor cursor(Int index = 0) {
return new IndexCursor(index);
}
/**
* A Cursor is a stateful, mutable navigator of a List. It can be used to walk through a list in
* either direction, to randomly-access the list by altering its [index], can replace the
* the values of elements in the list, insert or append new elements into the list, or delete
* elements from the list.
*/
interface Cursor
extends Iterator<Element> {
// ----- metadata ----------------------------------------------------------------------
/**
* The containing list.
*/
@RO List list.get() {
return this.List;
}
/**
* Metadata: `True` iff the Cursor can move in reverse in an efficient manner.
*/
@RO Boolean bidirectional.get() {
return True;
}
// ----- Iterator methods --------------------------------------------------------------
/**
* Return the current element [value] and advance the `Cursor` to the next element.
*
* @return True iff `exists`
* @return (conditional) the `Element` [value] that the `Cursor` was situated on
*/
@Override
conditional Element next() {
if (exists) {
Element value = this.value;
advance();
return True, value;
}
return False;
}
// ----- Cursor operations -------------------------------------------------------------
/**
* The current index of the cursor within the list, which is a value between `0`
* (inclusive) and `size` (inclusive). If the index is equal to `size`, then the
* cursor is "beyond the end of the list", and refers to a non-existent element.
*
* @throws OutOfBounds if an attempt is made to set the index to a position less than