fix reduce

This commit is contained in:
Yadunand Prem 2022-11-02 23:23:27 +08:00
parent 345acc6329
commit 11af648bdf
2 changed files with 13 additions and 23 deletions

View File

@ -1,22 +1,13 @@
import java.util.ArrayList;
import java.util.List;
import cs2030s.fp.InfiniteList;
public class MyTest {
public static void main(String[] args) {
List<Integer> generateHistory = new ArrayList<>();
List<Integer> doublerHistory = new ArrayList<>();
InfiniteList.generate(() -> {
generateHistory.add(1);
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());
InfiniteList<Integer> list = InfiniteList.iterate(1, x -> x + 1);
System.out.println(list.takeWhile(x -> x < 10).reduce(0, (x, y) -> {
System.out.println("vals: x: " + x + " y: " + y);
return x + y;
}));
}
}

View File

@ -80,21 +80,20 @@ public class InfiniteList<T> {
}
public List<T> toList() {
List<T> arrayList = new ArrayList<>();
arrayList.add(this.head());
arrayList.addAll(this.tail().toList());
return arrayList;
return this.reduce(new ArrayList<>(), (acc, i) -> {
acc.add(i);
return 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,
// this.tail.tail.head to acc, until finally id to acc
// return acc.combine(this., acc)
return null;
return this.head.get().transform((h) -> this.tail.get().reduce(acc.combine(id, this.head.get().unless(null)), acc))
.except(() -> this.tail.get().reduce(id, acc));
}
public long count() {
return this.reduce(0L, (a, b) -> a + 1);
return this.reduce(0L, (a, b) -> a + 1L);
}
@Override