/
ImmutableList.java
90 lines (67 loc) · 1.81 KB
/
ImmutableList.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
package ipogudin.fp;
import java.util.function.Function;
public class ImmutableList<T> implements Functor<T> {
public static final ImmutableList EMPTY_IMMUTABLE_LIST = new EmptyImmutableList();
private T head;
private ImmutableList<T> tail;
public ImmutableList(T head, ImmutableList<T> tail) {
this.head = head;
this.tail = tail;
}
public ImmutableList(T head) {
this(head, EMPTY_IMMUTABLE_LIST);
}
public T head() {
return head;
}
public ImmutableList<T> tail() {
return tail;
}
@Override
public <U> ImmutableList<U> map(Function<T, U> f) {
return new ImmutableList<U>(f.apply(head), tail.map(f));
}
public ImmutableList<T> add(T newHead) {
if (newHead == null) {
return this;
}
return new ImmutableList<>(newHead, this);
}
public ImmutableList<T> reverse() {
return EMPTY_IMMUTABLE_LIST.addAll(this);
}
public ImmutableList<T> addAll(ImmutableList<T> l) {
if (l == null) {
return this;
}
return add(l.head).addAll(l.tail);
}
public int size() {
return tail.size() + 1;
}
@Override
public String toString() {
return ((tail == EMPTY_IMMUTABLE_LIST) ? "" : tail.toString() + ", ") + head ;
}
public static class EmptyImmutableList extends ImmutableList {
public EmptyImmutableList() {
super(null);
}
@Override
public Object head() {
return null;
}
@Override
public ImmutableList map(Function f) {
return this;
}
@Override
public int size() {
return 0;
}
@Override
public String toString() {
return "";
}
}
}