java - 如何在没有循环且仅使用 foldLeft 的情况下获得 minVal?
问题描述
因此,我对函数式编程有了一些了解,但为此我不能使用循环,而是必须使用我编写的 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 中的比较器,但不明白如何在测试(或打印语句)中实现它。
任何帮助/解释表示赞赏!PS如果我遗漏任何信息,请告诉我,我试图尽可能彻底。
解决方案
您可以将minVal
using定义foldLeft
为:
static <U> U minVal(Iterable<U> l, Comparator<U> c) {
// write using fold. No other loops permitted.
return foldLeft(l.iterator().next(), l, (u, u2) -> c.compare(u, u2) < 0 ? u : u2);
// check for l.iterator().hasNext() or else define the behaviour
}
然后使用以下Comparator<Integer
定义调用它:
List<Integer> numList = List.of(5, 10, 15, 20, 22, 1);
System.out.println(minVal(numList, Integer::compare));
推荐阅读
- javascript - 如何使用 Ionic Capacitor 启用捏缩放?
- python - 如何使用生成器训练 XGBoost?
- powerbi - 根据在 Power BI 中搜索单独字段查找周围的索引记录
- react-native - chrome调试器打开时反应本机应用程序崩溃
- spring-boot - 是否可以在运行时重新启动 Hikari 数据源
- javascript - 按键顺序对对象进行分组
- node.js - 使用 Prisma 进行深度嵌套事务写入
- python - 并行 Python 代码在 Replit 上运行良好,但在本地失败
- typescript - 使用自定义节点模块在 RTL 中运行意外令牌“导出”测试
- python - 将基本物理实现到一个简单的 2d pygame(仅限惯性和重力)