fix reduce
This commit is contained in:
@@ -1,22 +1,13 @@
|
|||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import cs2030s.fp.InfiniteList;
|
import cs2030s.fp.InfiniteList;
|
||||||
|
|
||||||
public class MyTest {
|
public class MyTest {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
List<Integer> generateHistory = new ArrayList<>();
|
InfiniteList<Integer> list = InfiniteList.iterate(1, x -> x + 1);
|
||||||
List<Integer> doublerHistory = new ArrayList<>();
|
System.out.println(list.takeWhile(x -> x < 10).reduce(0, (x, y) -> {
|
||||||
InfiniteList.generate(() -> {
|
System.out.println("vals: x: " + x + " y: " + y);
|
||||||
generateHistory.add(1);
|
return x + y;
|
||||||
return 1;
|
}));
|
||||||
}).map(x -> {
|
|
||||||
doublerHistory.add(x);
|
|
||||||
return x * 2;
|
|
||||||
}).tail().head();
|
|
||||||
System.out.println(generateHistory);
|
|
||||||
System.out.println(doublerHistory);
|
|
||||||
System.out.println(InfiniteList.iterate(1, x -> x + 1).filter(x -> x % 2 == 0).head());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -80,21 +80,20 @@ public class InfiniteList<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<T> toList() {
|
public List<T> toList() {
|
||||||
List<T> arrayList = new ArrayList<>();
|
return this.reduce(new ArrayList<>(), (acc, i) -> {
|
||||||
arrayList.add(this.head());
|
acc.add(i);
|
||||||
arrayList.addAll(this.tail().toList());
|
return acc;
|
||||||
return arrayList;
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public <U> U reduce(U id, Combiner<U, U, ? super T> acc) {
|
public <U> U reduce(U id, Combiner<U, U, ? super T> acc) {
|
||||||
// reduce by applying this.head to acc, this.tail.head to acc,
|
return this.head.get().transform((h) -> this.tail.get().reduce(acc.combine(id, this.head.get().unless(null)), acc))
|
||||||
// this.tail.tail.head to acc, until finally id to acc
|
.except(() -> this.tail.get().reduce(id, acc));
|
||||||
// return acc.combine(this., acc)
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public long count() {
|
public long count() {
|
||||||
return this.reduce(0L, (a, b) -> a + 1);
|
return this.reduce(0L, (a, b) -> a + 1L);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
Reference in New Issue
Block a user