-
Notifications
You must be signed in to change notification settings - Fork 3
/
PStream.recaf
95 lines (76 loc) · 2.11 KB
/
PStream.recaf
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
package generated;
import recaf.demo.cps.Iter;
import java.util.stream.IntStream;
import java.util.Iterator;
import java.util.function.Predicate;
import java.util.function.*;
import java.util.NoSuchElementException;
public class PStream {
public PStream(Iterable<Integer> source) {
super();
this.source = source;
}
Iterable<Integer> source;
public static PStream range(int n) {
return new PStream(rangeIter(n));
}
private static Iterable<Integer> rangeIter(int n) {
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return IntStream.range(0, n).iterator();
}
};
}
public static PStream of(Integer[] array) {
return new PStream(ofIter(array));
}
private static Iterable<Integer> ofIter(Integer[] array) {
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
final int size = array.length;
int cursor = 0;
@Override
public boolean hasNext() {
return cursor != size;
}
@Override
public Integer next() {
if (cursor >= size)
throw new NoSuchElementException();
return array[cursor++];
}
};
};
};
}
public PStream filter(Predicate<Integer> pred) {
return new PStream(filterIter(this.source, pred));
}
private recaf Iter<Integer> alg = new Iter<Integer>();
recaf Iterable<Integer> filterIter(Iterable<Integer> source, Predicate<Integer> pred) {
for (Integer t: source) {
if (pred.test(t)) {
yield! t;
}
}
}
public PStream map(Function<Integer, Integer> f) {
return new PStream(mapIter(this.source, f));
}
recaf Iterable<Integer> mapIter(Iterable<Integer> source, Function<Integer, Integer> f) {
for (Integer t: source) {
yield! f.apply(t);
}
}
public Integer sum() {
return sumIter(this.source);
}
private Integer sumIter(Iterable<Integer> source) {
Integer acc = 0;
for (Integer t: source) {
acc+=t;
}
return acc;
}
}