首页 > 解决方案 > 如何在没有循环且仅使用 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如果我遗漏任何信息,请告诉我,我试图尽可能彻底。

标签: javaooplambdafunctional-programming

解决方案


您可以将minValusing定义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));

推荐阅读