- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava_without_closures.java
More file actions
Latest commit
65 lines (56 loc) · 1.54 KB
/
Copy pathjava_without_closures.java
File metadata and controls
65 lines (56 loc) · 1.54 KB
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
interfaceFunc<B,A> {
Bm(Ax);
}
interfacePred<A> {
booleanm(Ax);
}
classList<T> {
Thead;
List<T> tail;
List(Tx, List<T> xs) {
head = x;
tail = xs;
}
// * the advantage of a static method is it allows xs to be null
// -- a more OO way would be a subclass for empty lists
// * a more effcient way in Java would be a messy while loop
// where you keep a pointer to the previous element and mutate it
// --(try it if you do not blieve it is messy)
static <A,B> List<B> map(Func<B,A> f, List<A> xs) {
if(xs==null)
returnnull;
returnnewList<B>(f.m(xs.head), map(f,xs.tail));
}
static <A> List<A> filter(Pred<A> f, List<A> xs) {
if(xs==null)
returnnull;
if(f.m(xs.head))
returnnewList<A>(xs.head, filter(f,xs.tail));
returnfilter(f,xs.tail);
}
// * again recursion would be more elegant but less efficient
// * again an instance method be more common, but then
// all clients have to special-case null
static <A> intlength(List<A> xs) {
intans = 0;
while(xs != null) {
++ans;
xs = xs.tail;
}
returnans;
}
}
classExampleClients {
staticList<Integer> doubleAll(List<Integer> xs) {
returnList.map((newFunc<Integer,Integer>() {
publicIntegerm(Integerx) {returnx * 2;}
}), xs);
}
staticintcountNs(List<Integer> xs, finalintn) {
returnList.length(List.filter(
(newPred<Integer>() {
publicbooleanm(Integerx)
{ returnx==n;}
}), xs));
}
}