【发布时间】:2020-05-12 10:50:33
【问题描述】:
所以,我对函数式编程有了一些了解,但为此我不能使用循环,而是必须使用我编写的 foldLeft 或 foldRight 函数来获取 minVal。
static <U,V> V foldLeft(V e, Iterable<U>l, BiFunction<V,U,V> f){
for(U u:l) {
e = f.apply(e, u);
}
return e;
}
static <U,V> V foldRight(V e, Iterable<U>l, BiFunction<U,V,V> f){
for(U u:l) {
e = f.apply(u, e);
}
return e;
我现在必须写一个 minVal:
//(5) Use minVal to calculate the minimum of a List of
// Integers
static <U> U minVal(Iterable<U> l, Comparator<U> c){
// write using fold. No other loops permitted.
List<U> temp = new ArrayList<U>();
l.forEach(temp::add);
return temp.stream().min(c).get(); //Not sure if this actually works yet
}
我试图写这个并测试它,但我现在也被困在我要测试 minVal 的问题上:
List<Integer> numList = new ArrayList<>();
numList.add(5);
numList.add(10);
numList.add(15);
numList.add(20);
numList.add(22);
numList.add(1);
System.out.println(minVal(numList, 0)); //What would I place as the
//comparable argument
当然,上面的内容给了我一个错误。我已经阅读了 Lambda 中的比较器,但不明白如何在测试(或打印语句)中实现它。
感谢任何帮助/解释! 附言如果我遗漏任何信息,请告诉我,我尽量做到详尽。
【问题讨论】:
标签: java oop lambda functional-programming