/
IList.java
executable file
·827 lines (711 loc) · 23.8 KB
/
IList.java
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
package org.typemeta.funcj.data;
import org.typemeta.funcj.functions.Functions.*;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.*;
/**
* Simple recursive, immutable linked list.
* <p>
* Each {@code IList} is either {@link Empty} or it is {@link NonEmpty},
* in which case it has a head element value and a tail.
* The tail is itself an {@code IList}.
* Null elements are not allowed.
* @param <T> the element type
*/
public abstract class IList<T> implements Iterable<T> {
/**
* Construct an empty list.
* @param <T> the element type
* @return an empty list
*/
@SuppressWarnings("unchecked")
public static <T> IList<T> nil() {
return (IList<T>)Empty.EMPTY;
}
/**
* Construct an empty list.
* @param <T> the element type
* @return an empty list
*/
public static <T> IList<T> of() {
return nil();
}
/**
* Construct a list with one element.
* @param elem element
* @param <T> element type
* @return the new list with one element
*/
public static <T> NonEmpty<T> of(T elem) {
return IList.<T>nil().add(elem);
}
/**
* Construct a list with one or more elements.
* @param elem the first element
* @param elems the remaining elements
* @param <T> the element type
* @return the new list with one or more element
*/
@SafeVarargs
public static <T> NonEmpty<T> of(T elem, T... elems) {
return ofArray(elems).add(elem);
}
/**
* Construct a list from an {@link java.lang.Iterable} collection of elements.
* @param elems the iterable collection of elements
* @param <T> the element type
* @return the new list with multiple elements
*/
public static <T> IList<T> ofIterable(Iterable<T> elems) {
IList<T> r = nil();
for (T elem : elems) {
r = r.add(elem);
}
return r.reverse();
}
/**
* Construct a list from an array.
* @param elems the array of elements
* @param <T> the element type
* @return the new list with multiple elements
*/
public static <T> IList<T> ofArray(T[] elems) {
IList<T> r = nil();
for (int i = elems.length-1; i >= 0; --i) {
r = r.add(elems[i]);
}
return r;
}
/**
* Concatenate two lists to form a new list
* @param l1 the first list
* @param l2 the second list
* @param <T> the element type
* @return the new concatenated list
*/
public static <T> IList<T> concat(IList<? extends T> l1, IList<? extends T> l2) {
@SuppressWarnings("unchecked")
IList<T> r = (IList<T>)l2;
for (T elem : l1.reverse()) {
r = r.add(elem);
}
return r;
}
/**
* Convert a list of {@link java.lang.Character}s into a {@link java.lang.String}.
* @param l the list of {@code Character}s
* @return a {@code String}
*/
public static String listToString(IList<Character> l) {
final StringBuilder sb = new StringBuilder(l.size());
for (; !l.isEmpty(); l = l.tail()) {
sb.append(l.head());
}
return sb.toString();
}
/**
* Convert a {@link java.lang.String} into a list of {@link java.lang.Character}s.
* @param s the {@code String}
* @return a list of {@code Character}s
*/
public static IList<Character> stringToList(String s) {
IList<Character> r = nil();
for (int i = s.length() - 1; i >= 0; --i) {
r = r.add(s.charAt(i));
}
return r;
}
/**
* Kleisli models composable operations that return an {@code IList}.
* @param <T> the input type
* @param <U> the value type of the returned {@code IList} type
*/
@FunctionalInterface
interface Kleisli<T, U> {
/**
* Construct a {@code Kleisli} value from a function.
* @param f the function
* @param <T> the input type
* @param <U> the value type of the returned {@code Option} value
* @return the new {@code Kleisli}
*/
static <T, U> Kleisli<T, U> of(F<T, IList<U>> f) {
return f::apply;
}
/**
* Run this {@code Kleisli} operation
* @param t the input value
* @return the result of the operation
*/
IList<U> run(T t);
/**
* Compose this {@code Kleisli} with another by applying this one first,
* then the other.
* @param kUV the {@code Kleisli} to be applied after this one
* @param <V> the second {@code Kleisli}'s return type
* @return the composed {@code Kleisli}
*/
default <V> Kleisli<T, V> andThen(Kleisli<U, V> kUV) {
return t -> run(t).flatMap(kUV::run);
}
/**
* Compose this {@code Kleisli} with another by applying the other one first,
* and then this one.
* @param kST the {@code Kleisli} to be applied after this one
* @param <S> the first {@code Kleisli}'s input type
* @return the composed {@code Kleisli}
*/
default <S> Kleisli<S, U> compose(Kleisli<S, T> kST) {
return s -> kST.run(s).flatMap(this::run);
}
/**
* Compose this {@code Kleisli} with a function,
* by applying this {@code Kleisli} first,
* and then mapping the function over the result.
* @param f the function
* @param <V> the function return type
* @return the composed {@code Kleisli}
*/
default <V> Kleisli<T, V> map(F<U, V> f) {
return t -> run(t).map(f);
}
}
/**
* Create a new list by adding an element to the head of this list.
* @param head the element to add onto head of this list
* @return the new list
*/
public NonEmpty<T> add(T head) {
return new NonEmpty<T>(head, this);
}
/**
* Create a new list by adding multiple elements to the head of this list.
* @param l the list to be added to the head of this list
* @param <S> the list element type
* @return the new list
*/
public <S extends T> IList<T> addAll(IList<S> l) {
IList<T> r = this;
for(IList<S> next = l.reverse(); !next.isEmpty(); next = next.tail()) {
r = r.add(next.head());
}
return r;
}
/**
* Return true if this list is empty otherwise false
* @return true if this list is empty otherwise false
*/
public abstract boolean isEmpty();
/**
* Returns Optional.empty() if this list is empty,
* otherwise it returns an {@link java.util.Optional} which wraps the non-empty list.
* @return the Optional.empty() if this list is empty, otherwise an {@code Optional} which wraps the
* non-empty list.
*/
public abstract Optional<NonEmpty<T>> nonEmptyOpt();
/**
* Return the head element of this list.
* @return the head of this list.
* @throws UnsupportedOperationException if the list is empty.
*/
public abstract T head();
/**
* Return the tail of this list.
* @return the tail of this list.
* @throws UnsupportedOperationException if the list is empty.
*/
public abstract IList<T> tail();
/**
* Returns the element at the specified position in this list.
* @param index the position of the element to return
* @return the element of this list at the specified position.
* @throws IndexOutOfBoundsException if the index is out of bounds.
*/
public abstract T get(int index);
/**
* Append the contents of this list to a {@link java.lang.StringBuilder}.
* @param sb the StringBuilder to be appended to
* @return the StringBuilder
*/
public abstract StringBuilder append(StringBuilder sb);
/**
* List equality.
* @return true if this list and rhs are equal in terms of their size and elements.
*/
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object rhs) {
return this == rhs ||
(rhs != null &&
getClass() == rhs.getClass() &&
equals((IList<T>) rhs));
}
/**
* Type-safe list equality.
* @param rhs the list to be cpmpared
* @return true if this list and rhs are equal in terms of their elements.
*/
public abstract boolean equals(IList<T> rhs);
/**
* Apply one of two functions depending on whether this list is empty or not.
* @param nonEmptyF the function to be applied if the list is non-empty
* @param emptyF the function to be applied if the list is empty
* @param <S> return type of both functions
* @return the result of applying the appropriate function.
*/
public abstract <S> S match(F<NonEmpty<T>, S> nonEmptyF, F<Empty<T>, S> emptyF);
/**
* Create a new list by appending an element to the end of this list.
* @param l the list to be appended to the end of this list
* @return the new list
*/
public abstract IList<T> appendAll(IList<? extends T> l);
/**
* @return the length of this list.
*/
public abstract int size();
/**
* @return this list in reverse.
*/
public abstract IList<T> reverse();
/**
* Apply the function {@code f} to each element in this list,
* and store the results in a new list.
* @param f the function to be applied to each element
* @param <U> the function return type
* @return the new list
*/
public abstract <U> IList<U> map(F<? super T, ? extends U> f);
/**
* Apply a function that returns an {@code IList} to each element
* in this list and concatenate the results into a single list.
* @param f the function to be applied
* @param <U> the element type for the list returned by the function
* @return the new list
*/
public abstract <U> IList<U> flatMap(F<? super T, IList<? extends U>> f);
/**
* Right-fold a function over this list.
* @param f the function to be folded
* @param z the initial value for the fold (typically the identity value of {@code f})
* @param <U> the fold result type
* @return the folded result
*/
public abstract <U> U foldRight(F2<T, U, U> f, U z);
/**
* Left-fold a function over this list.
* @param f the function to be folded
* @param z the initial value for the fold (typically the identity value of {@code f})
* @param <U> the fold result type
* @return the folded result
*/
public abstract <U> U foldLeft(F2<U, T, U> f, U z);
/**
* Create a {@link java.util.Spliterator}.
* @return the spliterator
*/
public abstract Spliterator<T> spliterator();
/**
* Create a {@link java.util.stream.Stream} onto this list.
* @return the new stream
*/
public Stream<T> stream() {
return StreamSupport.stream(spliterator(), false);
}
/**
* Create a parallel {@link java.util.stream.Stream} onto this list.
* @return the new stream
*/
public Stream<T> parallelStream() {
return StreamSupport.stream(spliterator(), true);
}
/**
* Create an {@link java.util.Iterator} over this list.
* @return the iterator
*/
public abstract Iterator<T> iterator();
/**
* Convert to a Java List implementation, albeit an immutable one.
* @return the Java List.
*/
public abstract List<T> toList();
/**
* An empty list node.
* @param <T> the element type
*/
public static final class Empty<T> extends IList<T> {
static final Empty<?> EMPTY = new Empty<Void>();
private Empty() {
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public Optional<NonEmpty<T>> nonEmptyOpt() {
return Optional.empty();
}
@Override
public T head() {
throw new UnsupportedOperationException("Cannot take the head of an empty list");
}
@Override
public IList<T> tail() {
throw new UnsupportedOperationException("Cannot take the tail of an empty list");
}
@Override
public T get(int index) {
throw new IndexOutOfBoundsException(
"Index " + index + " out of bounds for an " + size() + " element list");
}
@Override
public String toString() {
return "[]";
}
@Override
public boolean equals(IList<T> rhs) {
return rhs.isEmpty();
}
@Override
public int hashCode() {
return 0;
}
@Override
public StringBuilder append(StringBuilder sb) {
return sb;
}
@Override
public <S> S match(F<NonEmpty<T>, S> nonEmptyF, F<Empty<T>, S> emptyF) {
return emptyF.apply(this);
}
@Override
@SuppressWarnings("unchecked")
public IList<T> appendAll(IList<? extends T> l) {
return (IList<T>)l;
}
@Override
public int size() {
return 0;
}
@Override
public IList<T> reverse() {
return nil();
}
@Override
public <U> IList<U> map(F<? super T, ? extends U> f) {
return nil();
}
@Override
public <U> IList<U> flatMap(F<? super T, IList<? extends U>> f) {
return nil();
}
@Override
public <U> U foldRight(F2<T, U, U> f, U z) {
return z;
}
@Override
public <U> U foldLeft(F2<U, T, U> f, U z) {
return z;
}
@Override
public Spliterator<T> spliterator() {
return new Spliterator<T>() {
@Override
public boolean tryAdvance(Consumer<? super T> action) {
return false;
}
@Override
public Spliterator<T> trySplit() {
return null;
}
@Override
public long estimateSize() {
return size();
}
@Override
public int characteristics() {
return Spliterator.IMMUTABLE + Spliterator.SIZED;
}
};
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>(){
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
throw new NoSuchElementException();
}
};
}
@Override
public List<T> toList() {
return Collections.emptyList();
}
}
/**
* A non-empty list node.
* @param <T> the element type
*/
public static final class NonEmpty<T> extends IList<T> {
private final T head;
private final IList<T> tail;
NonEmpty(T head, IList<T> tail) {
this.head = Objects.requireNonNull(head);
this.tail = Objects.requireNonNull(tail);
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Optional<NonEmpty<T>> nonEmptyOpt() {
return Optional.of(this);
}
@Override
public T head() {
return head;
}
@Override
public IList<T> tail() {
return tail;
}
@Override
public T get(int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index " + index + " out of bounds");
} else if (index == 0) {
return head;
} else {
IList<T> next = tail;
for (int i = 1; i < index; ++i) {
if (next.isEmpty()) {
throw new IndexOutOfBoundsException("Index " + index + " out of bounds");
} else {
next = ((NonEmpty<T>)next).tail;
}
}
if (next.isEmpty()) {
throw new IndexOutOfBoundsException("Index " + index + " out of bounds");
} else {
return ((NonEmpty<T>)next).head;
}
}
}
@Override
public String toString() {
final StringBuilder r = new StringBuilder("[");
append(r).setCharAt(r.length() - 1, ']');
return r.toString();
}
@Override
public StringBuilder append(StringBuilder sb) {
return tail.append(sb.append(head).append(','));
}
@Override
public boolean equals(IList<T> rhs) {
if (rhs.isEmpty()) {
return false;
} else {
for (T lhs : this) {
if (rhs.isEmpty() || !lhs.equals(rhs.head())) {
return false;
}
rhs = rhs.tail();
}
return rhs.isEmpty();
}
}
@Override
public int hashCode() {
int hashCode = 1;
for(T elem : this) {
hashCode = 31 * hashCode + elem.hashCode();
}
return hashCode;
}
@Override
public <S> S match(F<NonEmpty<T>, S> nonEmptyF, F<Empty<T>, S> emptyF) {
return nonEmptyF.apply(this);
}
@Override
public IList<T> appendAll(IList<? extends T> l) {
return new NonEmpty<T>(head, tail.appendAll(l));
}
@Override
public int size() {
IList<T> pos = this;
int length = 0;
while (!pos.isEmpty()) {
++length;
pos = pos.tail();
}
return length;
}
@Override
public NonEmpty<T> reverse() {
IList<T> r = IList.of();
for (IList<T> n = this; !n.isEmpty(); n = n.tail()) {
r = r.add(n.head());
}
return (NonEmpty<T>)r;
}
@Override
public <U> NonEmpty<U> map(F<? super T, ? extends U> f) {
IList<U> r = nil();
for (IList<T> n = this; !n.isEmpty(); n = n.tail()) {
r = r.add(f.apply(n.head()));
}
return (NonEmpty<U>) r.reverse();
}
@Override
public <U> NonEmpty<U> flatMap(F<? super T, IList<? extends U>> f) {
final IList<U> r = nil();
for (IList<T> n = this; !n.isEmpty(); n = n.tail()) {
r.addAll(f.apply(n.head()));
}
return (NonEmpty<U>) r;
}
@Override
public <U> U foldRight(F2<T, U, U> f, U z) {
return reverse().foldLeft(f.flip(), z);
}
@Override
public <U> U foldLeft(F2<U, T, U> f, U z) {
U r = z;
for (IList<T> n = this; !n.isEmpty(); n = n.tail()) {
r = f.apply(r, n.head());
}
return r;
}
/**
* Right-fold a function over this non-empty list.
* @param f the function to be folded
* @return the folded result
*/
public T foldRight1(Op2<T> f) {
return reverse().foldLeft1(f.flip());
}
/**
* Left-fold a function over this non-empty list.
* @param f the function to be folded
* @return the folded result
*/
public T foldLeft1(Op2<T> f) {
T r = head;
for (IList<T> n = tail; !n.isEmpty(); n = n.tail()) {
r = f.apply(r, n.head());
}
return r;
}
@Override
public Spliterator<T> spliterator() {
return Spliterators.spliterator(
this.iterator(),
size(),
Spliterator.IMMUTABLE + Spliterator.SIZED
);
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>(){
IList<T> n = NonEmpty.this;
@Override
public boolean hasNext() {
return !n.isEmpty();
}
@Override
public T next() {
final T head = n.head();
n = n.tail();
return head;
}
};
}
@Override
public List<T> toList() {
return new ListAdaptor<T>(this);
}
}
private static class ListAdaptor<T> extends AbstractSequentialList<T> {
private final IList<T> impl;
private final int size;
ListAdaptor(IList<T> impl) {
this.impl = impl;
size = impl.size();
}
@Override
public ListIterator<T> listIterator(int index) {
return new ListIterator<T>() {
private IList<T> move(IList<T> node, int count) {
for (int i = 0; i < count; ++i) {
node = node.tail();
}
return node;
}
private int pos = index;
private IList<T> node = move(impl, index);
@Override
public boolean hasNext() {
return pos < size;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
} else {
final T ret = node.head();
node = node.tail();
++pos;
return ret;
}
}
@Override
public boolean hasPrevious() {
return pos >= 0;
}
@Override
public T previous() {
if (!hasPrevious()) {
throw new NoSuchElementException();
} else {
--pos;
node = move(impl, pos);
++pos;
return node.head();
}
}
@Override
public int nextIndex() {
return pos;
}
@Override
public int previousIndex() {
return pos - 1;
}
@Override
public void remove() {
throw modError();
}
@Override
public void set(T t) {
throw modError();
}
@Override
public void add(T t) {
throw modError();
}
private UnsupportedOperationException modError() {
return new UnsupportedOperationException("IList can not be modified");
}
};
}
@Override
public int size() {
return size;
}
}
}