-
Notifications
You must be signed in to change notification settings - Fork 2
/
combinator-collections.grace
1704 lines (1618 loc) · 56.5 KB
/
combinator-collections.grace
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
import "platform/memory" as mem
def ProgrammingError is public = Exception.refine "ProgrammingError"
def BoundsError is public = ProgrammingError.refine "BoundsError"
def IteratorExhausted is public = ProgrammingError.refine "IteratorExhausted"
def SubobjectResponsibility is public = ProgrammingError.refine "SubobjectResponsibility"
def NoSuchObject is public = ProgrammingError.refine "NoSuchObject"
def RequestError is public = ProgrammingError.refine "RequestError"
def ConcurrentModification is public = ProgrammingError.refine "ConcurrentModification"
def SizeUnknown is public = Exception.refine "SizeUnknown"
//kjx hacks for Kernan
method sizeOfVariadicList( l ) {
var s := 0
for (l) do { _ -> s := s + 1 }
return s
}
method abs( n ) { //used only with %. Should at least be absmod...
if (n < 0) then {- n} else {n}
}
trait equalityTrait {
method ==(other) { abstract }
method !=(other) { ! (self == other) } //KERNAN
}
method blerg { def x = 3 }
def done = blerg
//kjx end hacks
method abstract {
// repeated in StandardPrelude
SubobjectResponsibility.raise "abstract method not overriden by subobject"
}
type Block0[[R]] = interface {
apply -> R
}
type Block1[[T,R]] = interface {
apply(a:T) -> R
}
type Block2[[S,T,R]] = interface {
apply(a:S, b:T) -> R
}
type Self = Unknown // becuase it's not yet in the language
type Object = interface { } //KERNAN
type Iterable[[T]] = Object & interface {
iterator -> Iterator[[T]]
// the iterator on which I am based
isEmpty -> Boolean
// true if I have no elements
first -> T
// my first element; raises BoundsError if I have none.
do(block1: Block1[[T, Done]]) -> Done
// an internal iterator; applies block1 to each of my elements
do(body:Block1[[T, Done]]) separatedBy(separator:Block0[[Done]]) -> Done
// an internal iterator; ; applies block1 to each of my elements, and applies separator in between
++(other: Iterable[[T]]) -> Iterable[[T]]
// returns a new iterator over the concatenation of self and other
fold(binaryFunction:Block2[[T, T, T]]) startingWith(initial:T) -> Object
// the left-associative fold of binaryFunction over self, starting with initial
map[[U]](function:Block1[[T, U]]) -> Iterator[[U]]
// returns a new iterator that yields my elements mapped by function
filter(condition:Block1[[T,Boolean]]) -> Iterator[[T]]
// returns a new iterator that yields those of my elements for which condition holds
}
type Expandable[[T]] = Iterable[[T]] & interface {
//add(*x: T) -> Self
addAll(xs: Iterable[[T]]) -> Self
}
type Collection[[T]] = Iterable[[T]] & interface {
asList -> List[[T]]
asSequence -> Sequence[[T]]
asSet -> Set[[T]]
}
type Enumerable[[T]] = Collection[[T]] & interface {
values -> Collection[[T]]
asDictionary -> Dictionary[[Number,T]]
keysAndValuesDo(action:Block2[[Number,T,Object]]) -> Done
onto(resultFactory:EmptyCollectionFactory[[T]]) -> Collection[[T]]
into(existing: Expandable[[Unknown]]) -> Collection[[Unknown]]
sortedBy(comparison:Block2[[T,T,Number]]) -> Self
sorted -> Self
}
type Sequence[[T]] = Enumerable[[T]] & interface {
size -> Number
at(n:Number) -> T
// [ n:Number ] -> T //kernan
indices -> Sequence[[Number]]
keys -> Sequence[[Number]]
second -> T
third -> T
fourth -> T
fifth -> T
last -> T
indexOf[[W]](elem:T)ifAbsent(action:Block0[[W]]) -> Number | W
indexOf(elem:T) -> Number
contains(elem:T) -> Boolean
reversed -> Sequence[[T]]
}
type List[[T]] = Sequence[[T]] & interface {
// add(*x: T) -> List[[T]]
addAll(xs: Iterable[[T]]) -> List[[T]]
// addFirst(*x: T) -> List[[T]]
addAllFirst(xs: Iterable[[T]]) -> List[[T]]
// addLast(*x: T) -> List[[T]] // same as add
at(ix:Number) put(v:T) -> List[[T]]
//[]:= (ix:Number, v:T) -> Done // KERNAN
removeFirst -> T
removeAt(n: Number) -> T
removeLast -> T
// remove(*v:T)
// remove(*v:T) ifAbsent(action:Block0[[Done]])
removeAll(vs: Iterable[[T]])
removeAll(vs: Iterable[[T]]) ifAbsent(action:Block0[[Unknown]])
pop -> T
++(o: List[[T]]) -> List[[T]]
addAll(l: Iterable[[T]]) -> List[[T]]
copy -> List[[T]]
sort -> List[[T]]
sortBy(sortBlock:Block2[[T,T,Number]]) -> List[[T]]
reverse -> List[[T]]
reversed -> List[[T]]
}
type Set[[T]] = Collection[[T]] & interface {
size -> Number
// add(*elements:T) -> Self
addAll(elements: Iterable[[T]]) -> Self
// remove(*elements: T) -> Set[[T]]
// remove(*elements: T) ifAbsent(block: Block0[[Done]]) -> Set[[T]]
includes(booleanBlock: Block1[[T,Boolean]]) -> Boolean
find(booleanBlock: Block1[[T,Boolean]]) ifNone(notFoundBlock: Block0[[T]]) -> T
copy -> Set[[T]]
contains(elem:T) -> Boolean
** (other:Set[[T]]) -> Set[[T]]
-- (other:Set[[T]]) -> Set[[T]]
++ (other:Set[[T]]) -> Set[[T]]
removeAll(elems: Iterable[[T]])
removeAll(elems: Iterable[[T]])ifAbsent(action:Block0[[Done]]) -> Set[[T]]
onto(resultFactory:EmptyCollectionFactory[[T]]) -> Collection[[T]]
into(existing: Expandable[[Unknown]]) -> Collection[[Unknown]]
}
type Dictionary[[K,T]] = Collection[[T]] & interface {
size -> Number
containsKey(k:K) -> Boolean
containsValue(v:T) -> Boolean
contains(elem:T) -> Boolean
at(key:K)ifAbsent(action:Block0[[Unknown]]) -> Unknown
at(key:K)put(value:T) -> Dictionary[[K,T]]
// []:= (k:K, v:T) -> Done // KERNAN
at(k:K) -> T
// [ k:K ] -> T //kernan
removeAllKeys(keys: Iterable[[K]]) -> Dictionary[[K,T]]
//removeKey(*keys:K) -> Dictionary[[K,T]]
removeAllValues(removals: Iterable[[T]]) -> Dictionary[[K,T]]
//removeValue(*removals:T) -> Dictionary[[K,T]]
keys -> Enumerable[[K]]
values -> Enumerable[[T]]
bindings -> Enumerable[[Binding[[K,T]]>
keysAndValuesDo(action:Block2[[K,T,Done]]) -> Done
keysDo(action:Block1[[K,Done]]) -> Done
valuesDo(action:Block1[[T,Done]]) -> Done
== (other:Object) -> Boolean
copy -> Dictionary[[K,T]]
++ (other:Dictionary[[K, T]]) -> Dictionary[[K, T]]
-- (other:Dictionary[[K, T]]) -> Dictionary[[K, T]]
asDictionary -> Dictionary[[K, T]]
}
type Iterator[[T]] = interface {
hasNext -> Boolean
next -> T
}
type CollectionFactory[[T]] = interface {
withAll (elts: Iterable[[T]]) -> Collection[[T]]
// with (*elts:Object) -> Collection[[T]]
empty -> Collection[[T]]
}
type EmptyCollectionFactory[[T]] = interface {
empty -> Collection[[T]]
}
trait collectionFactoryTrait[[T]] {
method withAll(elts: Iterable[[T]]) -> Collection[[T]] { abstract }
//method with(*a:T) -> Unknown { self.withAll(a) }
method empty -> Unknown { self.withAll [] }
}
class lazySequenceOver[[T,R]](source: Iterable[[T]])
mappedBy(function:Block1[[T,R]]) -> Enumerable[[R]] is confidential {
inherit enumerableTrait[[T]]
class iterator {
def sourceIterator = source.iterator
method asString { "an iterator over a lazy map sequence" }
method hasNext { sourceIterator.hasNext }
method next { function.apply(sourceIterator.next) }
}
method size { source.size }
method isEmpty { source.isEmpty }
method asDebugString { "a lazy sequence mapping over {source}" }
}
class lazySequenceOver[[T]](source: Iterable[[T]])
filteredBy(predicate:Block1[[T,Boolean]]) -> Enumerable[[T]] is confidential {
inherit enumerableTrait[[T]]
class iterator {
var cache
var cacheLoaded := false
def sourceIterator = source.iterator
method asString { "an iterator over filtered {source}" }
method hasNext {
// To determine if this iterator has a next element, we have to find
// an acceptable element; this is then cached, for the use of next
if (cacheLoaded) then { return true }
try {
cache := nextAcceptableElement
cacheLoaded := true
} catch { ex:IteratorExhausted -> return false }
return true
}
method next {
if (cacheLoaded.not) then { cache := nextAcceptableElement }
cacheLoaded := false
return cache
}
method nextAcceptableElement is confidential {
// return the next element of the underlying iterator satisfying
// predicate; if there is none, raises IteratorExhausted.
while { true } do {
def outerNext = sourceIterator.next
def acceptable = predicate.apply(outerNext)
if (acceptable) then { return outerNext }
}
}
}
method asDebugString { "a lazy sequence filtering {source}" }
}
class iteratorConcat[[T]](left:Iterator[[T]], right:Iterator[[T]]) {
method next {
if (left.hasNext) then {
left.next
} else {
right.next
}
}
method hasNext {
if (left.hasNext) then { return true }
return right.hasNext
}
method asDebugString { "iteratorConcat of {left} and {right}" }
method asString { "an iterator over a concatenation" }
}
class lazyConcatenation[[T]](left, right) -> Enumerable[[T]]{
inherit enumerableTrait[[T]]
alias superAsString = asString
method iterator {
iteratorConcat(left.iterator, right.iterator)
}
method asDebugString { "lazy concatenation of {left} and {right}" }
method asString { superAsString }
method size { left.size + right.size } // may raise SizeUnknown
}
trait collectionTrait[[T]] {
use equalityTrait
method do { abstract }
method iterator { abstract }
method isEmpty {
// override if size is known
iterator.hasNext.not
}
method first {
def it = self.iterator
if (it.hasNext) then {
it.next
} else {
BoundsError.raise "no first element in {self}"
}
}
method do(block1) separatedBy(block0) {
var firstTime := true
var i := 0
self.do { each ->
if (firstTime) then {
firstTime := false
} else {
block0.apply
}
block1.apply(each)
}
return self
}
method reduce(initial, blk) {
// deprecated; for compatibility with builtInList
fold(blk)startingWith(initial)
}
method fold(blk)startingWith(initial) {
var result := initial
self.do {it ->
result := blk.apply(result, it)
}
return result
}
method map[[R]](block1:Block1[[T,R]]) -> Enumerable[[R]] {
lazySequenceOver(self) mappedBy(block1)
}
method filter(selectionCondition:Block1[[T,Boolean]]) -> Enumerable[[T]] {
lazySequenceOver(self) filteredBy(selectionCondition)
}
method iter { self.iterator }
method asSequence {
sequence.withAll(self)
}
method asList {
list.withAll(self)
}
method asSet {
set.withAll(self)
}
}
trait enumerableTrait[[T]] {
use collectionTrait[[T]]
method iterator { abstract }
method size {
// override if size is known
SizeUnknown.raise "size requested on {asString}"
}
method asDictionary {
def result = dictionary.empty
keysAndValuesDo { k, v ->
result.at(k) put(v)
}
return result
}
method onto(f: CollectionFactory[[T]]) -> Collection[[T]] {
f.withAll(self)
}
method into(existing: Expandable[[T]]) -> Collection[[T]] {
def selfIterator = self.iterator
while {selfIterator.hasNext} do {
existing.add(selfIterator.next)
}
existing
}
method ==(other) {
isEqual (self) toIterable (other)
}
method do(block1:Block1[[T,Done]]) -> Done {
def selfIterator = self.iterator
while {selfIterator.hasNext} do {
block1.apply(selfIterator.next)
}
}
method keysAndValuesDo(block2:Block2[[Number,T,Done]]) -> Done {
var ix := 0
def selfIterator = self.iterator
while {selfIterator.hasNext} do {
ix := ix + 1
block2.apply(ix, selfIterator.next)
}
}
method values -> Collection[[T]] {
self
}
method fold[[R]](block2)startingWith(initial) -> R {
var res := initial
def selfIterator = self.iterator
while { selfIterator.hasNext } do {
res := block2.apply(res, selfIterator.next)
}
return res
}
method ++ (other) -> Enumerable[[T]] {
lazyConcatenation(self, other)
}
method sortedBy(sortBlock:Block2) -> List[[T]] {
self.asList.sortBy(sortBlock)
}
method sorted -> List[[T]] {
self.asList.sort
}
method asString {
var s := "⟨"
do { each -> s := s ++ each.asString } separatedBy { s := s ++ ", " }
s ++ "⟩"
}
}
trait indexableTrait[[T]] {
use collectionTrait[[T]]
method at { abstract }
method size { abstract }
method isEmpty { size == 0 }
method keysAndValuesDo(action:Block2[[Number,T,Done]]) -> Done {
def curSize = size
var i := 1
while {i <= curSize} do {
action.apply(i, self.at(i))
i := i + 1
}
}
method first { at(1) }
method second { at(2) }
method third { at(3) }
method fourth { at(4) }
method fifth { at(5) }
method last { at(size) }
// method [ix] { at(ix) } //kernan
method indices { range.from 1 to(size) }
method indexOf(sought:T) {
indexOf(sought) ifAbsent { NoSuchObject.raise "{sought} not in collection" }
}
method indexOf(sought:T) ifAbsent(action:Block0) {
keysAndValuesDo { ix, v ->
if (v == sought) then { return ix }
}
action.apply
}
method asDictionary {
def result = dictionary.empty
keysAndValuesDo { k, v ->
result.at(k) put(v)
}
return result
}
method onto(f: CollectionFactory[[T]]) -> Collection[[T]] {
f.withAll(self)
}
method into(existing: Expandable[[T]]) -> Collection[[T]] {
def selfIterator = self.iterator
while {selfIterator.hasNext} do {
existing.add(selfIterator.next)
}
existing
}
}
method max(a,b) is confidential { // repeated from standard prelude
if (a > b) then { a } else { b }
}
def emptySequence is confidential = object {
inherit indexableTrait
method size { 0 }
method isEmpty { true }
method at(n) { BoundsError.raise "index {n} of empty sequence" }
// method [n] { BoundsError.raise "index {n} of empty sequence" } //kernan
method keys { self }
method values { self }
method keysAndValuesDo(block2) { done }
method reversed { self }
method ++(other: Iterable) { sequence.withAll(other) }
method asString { "⟨⟩" }
method contains(element) { false }
method do(block1) { done }
method ==(other) {
match (other)
case {o: Iterable ->
o.isEmpty
}
case {_ ->
false
}
}
class iterator {
method asString { "emptySequenceIterator" }
method hasNext { false }
method next { IteratorExhausted.raise "on empty sequence" }
}
method sorted { self }
method sortedBy(sortBlock:Block2){ self }
}
class sequence[[T]] {
inherit collectionFactoryTrait[[T]]
method empty is override {
// this is an optimization: there need be just one empty sequence
emptySequence
}
method withAll(a: Iterable) {
var forecastSize := 0
var sizeUncertain := false
// size might be uncertain if one of the arguments is a lazy collection.
for (a) do { arg ->
try {
forecastSize := forecastSize + arg.size
} catch { _ ->
forecastSize := forecastSize + 8 //KERNAN
sizeUncertain := true //KERNAN
}
}
var inner := mem.allocate(forecastSize)
var innerSize := inner.size
var ix := 0
if (sizeUncertain) then {
// less-than-optimal path
for (a) do { arg ->
for (arg) do { elt ->
if (innerSize <= ix) then {
def newInner = mem.allocate(innerSize * 2)
for (0 .. (innerSize - 1)) do { i ->
newInner.at(i)put(inner.at(i))
}
inner := newInner
innerSize := inner.size
}
inner.at(ix)put(elt)
ix := ix + 1
}
}
} else {
// common, fast path
for (a) do { arg ->
for (arg) do { elt ->
inner.at(ix)put(elt)
ix := ix + 1
}
}
}
self.fromPrimitiveArray(inner, ix)
}
method fromPrimitiveArray(pArray, sz) is confidential {
// constructs a sequence from the first sz elements of pArray
object {
inherit indexableTrait
def size is public = sz
def inner = pArray
method boundsCheck(n) is confidential {
if (!(n >= 1) || !(n <= size)) then {
// the condition is written this way because NaN always
// compares false
BoundsError.raise "index {n} out of bounds 1 .. {size}"
}
}
method at(n) {
boundsCheck(n)
inner.at(n - 1)
}
method keys {
range.from(1)to(size)
}
method values {
self
}
method keysAndValuesDo(block2) {
var i := 0
while {i < size} do {
block2.apply(i + 1, inner.at(i))
i := i + 1
}
}
method reversed {
def freshArray = mem.allocate(size)
var ix := size - 1
do { each ->
freshArray.at (ix) put(each)
ix := ix - 1
}
outer.fromPrimitiveArray(freshArray, size)
}
method ++(other: Iterable) {
sequence.withAll(self, other)
}
method asString {
var s := "⟨"
for (0 .. (size - 1)) do {i->
s := s ++ inner.at(i).asString
if (i < (size - 1)) then { s := s ++ ", " }
}
s ++ "⟩"
}
method contains(element) {
do { each -> if (each == element) then { return true } }
return false
}
method do(block1) {
var i := 0
while {i < size} do {
block1.apply(inner.at(i))
i := i + 1
}
}
method ==(other) {
isEqual (self) toIterable (other)
}
method iterator {
object {
var idx := 1
method asDebugString { "{asString}⟪{idx}⟫" }
method asString { "aSequenceIterator" }
method hasNext { idx <= sz }
method next {
if (idx > sz) then { IteratorExhausted.raise "on sequence {outer.asString}⟪{idx}⟫" }
def ret = at(idx)
idx := idx + 1
ret
}
}
}
method sorted {
asList.sortBy { l, r ->
if (l == r) then {0}
elseif (l < r) then {-1}
else {1}
}.asSequence
}
method sortedBy(sortBlock:Block2){
asList.sortBy(sortBlock).asSequence
}
}
}
}
method isEqual(left) toIterable(right) {
if (Iterable.match(right)) then {
def leftIter = left.iterator
def rightIter = right.iterator
while {leftIter.hasNext && rightIter.hasNext} do {
if (leftIter.next != rightIter.next) then {
return false
}
}
leftIter.hasNext == rightIter.hasNext
} else {
false
}
}
class list[[T]] {
inherit collectionFactoryTrait[[T]]
method withAll(a: Iterable[[T]]) -> List[[T]] {
object {
// the new list object without native code
inherit indexableTrait[[T]]
var size is readable := 0 //KERNAN moved up from below
var mods is readable := 0
var initialSize
try { initialSize := sizeOfVariadicList(a) * 2 + 1 }
catch { _ex:SizeUnknown -> initialSize := 9 }
var inner := mem.allocate(initialSize)
for (a) do {x->
inner.at(size)put(x)
size := size + 1
}
method boundsCheck(n) is confidential {
if ( !(n >= 1) || !(n <= size)) then {
BoundsError.raise "index {n} out of bounds 1 .. {size}"
}
}
method at(n) {
boundsCheck(n)
inner.at(n - 1)
}
method at(n)put(x) {
mods := mods + 1
if (n == (size + 1)) then {
addLast(x)
} else {
boundsCheck(n)
inner.at(n - 1)put(x)
}
self
}
method add(e) { addAll [ e ] }
method addAll(l) {
mods := mods + 1
if ((size + sizeOfVariadicList(l)) > inner.size) then {
expandTo(max(size + sizeOfVariadicList(l), size * 2))
}
for (l) do {each ->
inner.at(size)put(each)
size := size + 1
}
self
}
method push(x) {
mods := mods + 1
if (size == inner.size) then { expandTo(inner.size * 2) }
inner.at(size)put(x)
size := size + 1
self
}
method removeLast {
mods := mods + 1
def result = inner.at(size - 1)
size := size - 1
result
}
method addAllFirst(l) {
mods := mods + 1
def increase = sizeOfVariadicList(l)
if ((size + increase) > inner.size) then {
expandTo(max(size + increase, size * 2))
}
for (range.from(size - 1)downTo(0)) do {i->
inner.at(i + increase)put(inner.at(i))
}
var insertionIndex := 0
for (l) do {each ->
inner.at(insertionIndex)put(each)
insertionIndex := insertionIndex + 1
}
size := size + increase
self
}
method removeFirst {
removeAt(1)
}
method removeAt(n) {
mods := mods + 1
boundsCheck(n)
def removed = inner.at(n - 1)
for (n .. (size - 1)) do {i->
inner.at(i - 1)put(inner.at(i))
}
size := size - 1
return removed
}
method remove(v:T) {
removeAll [ v ]
}
method remove(v:T) ifAbsent(action:Block0[[Done]]) {
removeAll [ v ] ifAbsent (action)
}
method removeAll(vs: Iterable[[T]]) {
removeAll(vs) ifAbsent { NoSuchObject.raise "object not in list" }
}
method removeAll(vs: Iterable[[T]]) ifAbsent(action:Block0[[Done]]) {
for (vs) do { each ->
def ix = indexOf(each) ifAbsent { 0 }
if (ix != 0) then {
removeAt(ix)
} else {
action.apply
}
}
self
}
method pop { removeLast }
method reversed {
def result = list.empty
do { each -> result.addFirst(each) }
result
}
method reverse {
mods := mods + 1
var hiIx := size
var loIx := 1
while {loIx < hiIx} do {
def hiVal = self.at(hiIx)
self.at(hiIx) put (self.at(loIx))
self.at(loIx) put (hiVal)
hiIx := hiIx - 1
loIx := loIx + 1
}
self
}
method ++(o) {
def l = list.withAll(self)
l.addAll(o)
}
method asString {
var s := "["
for (0 .. (size - 1)) do {i->
s := s ++ inner.at(i).asString
if (i < (size - 1)) then { s := s ++ ", " }
}
s ++ "]"
}
method contains(element) {
do { each -> if (each == element) then { return true } }
return false
}
method do(block1) {
var i := 0
while {i < size} do {
block1.apply(inner.at(i))
i := i + 1
}
}
method ==(other) {
isEqual (self) toIterable (other)
}
method iterator {
object {
var imods := mods
var idx := 1
method asDebugString { "{asString}⟪{idx}⟫" }
method asString { "aListIterator" }
method hasNext { idx <= size }
method next {
if (imods != mods) then {
ConcurrentModification.raise (asDebugString)
}
if (idx > size) then { IteratorExhausted.raise "on list" }
def ret = at(idx)
idx := idx + 1
ret
}
}
}
method values {
self
}
method keys {
self.indices
}
method expandTo(newSize) is confidential {
def newInner = mem.allocate(newSize)
for (0 .. (size - 1)) do {i->
newInner.at(i)put(inner.at(i))
}
inner := newInner
}
method sortBy(sortBlock:Block2) {
mods := mods + 1
// inner.sortInitial(size) by(sortBlock) //KERNNA: WTF???
self
}
method sort {
sortBy { l, r ->
if (l == r) then {0}
elseif (l < r) then {-1}
else {1}
}
}
method sortedBy(sortBlock:Block2) {
copy.sortBy(sortBlock)
}
method sorted {
copy.sort
}
method copy {
outer.withAll(self)
}
}
}
}
class set[[T]] {
inherit collectionFactoryTrait[[T]]
method withAll(a: Iterable[[T]]) -> Set[[T]] {
object {
inherit collectionTrait
var mods is readable := 0
var initialSize
try { initialSize := max(sizeOfVariadicList(a) * 3 + 1, 8) }
catch { _:SizeUnknown -> initialSize := 8 }
var inner := mem.allocate(initialSize)
def unused = object {
var unused := true
method asString { "unused" }
}
def removed = object {
var removed := true
method asString { "removed" }
}
var size is readable := 0
for (0 .. (initialSize - 1)) do {i->
inner.at(i)put(unused)
}
for (a) do { x-> add(x) }
method addAll(elements) {
mods := mods + 1
for (elements) do { x ->
if (! contains(x)) then {
def t = findPositionForAdd(x)
inner.at(t)put(x)
size := size + 1
if (size > (inner.size / 2)) then {
expand
}
}
}
self // for chaining
}
method add(elements) { addAll [ element ] }
method removeAll(elements) {
for (elements) do { x ->
remove (x) ifAbsent {
NoSuchObject.raise "set does not contain {x}"
}
}
self // for chaining
}
method removeAll(elements)ifAbsent(block) {
mods := mods + 1
for (elements) do { x ->
var t := findPosition(x)
if (inner.at(t) == x) then {
inner.at(t) put (removed)
size := size - 1
} else {
block.apply
}
}
self // for chaining
}
method remove(elements)ifAbsent(block) {
removeAll [ elements ] ifAbsent(block)
}
method remove(elements) {
removeAll [ elements ]
}
method contains(x) {
var t := findPosition(x)
if (inner.at(t) == x) then {
return true
}
return false
}
method includes(booleanBlock) {
self.do { each ->
if (booleanBlock.apply(each)) then { return true }
}
return false
}
method find(booleanBlock)ifNone(notFoundBlock) {
self.do { each ->
if (booleanBlock.apply(each)) then { return each }
}
return notFoundBlock.apply
}
method findPosition(x) is confidential {
def h = x.hash
def s = inner.size
var t := abs(h % s)
var jump := 5
var candidate
while {
candidate := inner.at(t)
candidate != unused
} do {
if (candidate == x) then {
return t
}
if (jump != 0) then {
t := abs((t * 3 + 1) % s)
jump := jump - 1
} else {
t := abs((t + 1) % s)
}
}
return t
}
method findPositionForAdd(x) is confidential {
def h = x.hash
def s = inner.size
var t := abs(h % s)
var jump := 5
var candidate
while {
candidate := inner.at(t)
(candidate != unused).andAlso{candidate != removed}
} do {
if (candidate == x) then {
return t
}
if (jump != 0) then {