本文介绍了我如何不使用循环而仅使用foldLeft来获得minVal?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我对函数式编程有了一些了解,但是为此,我不能使用循环,而必须使用我编写的foldLeft或foldRight函数才能获取minVal.

So, I have gotten a bit of an understanding of functional programming but for this I cannot use a loop and instead have to use the foldLeft or foldRight function that I wrote, on order to get the 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:

I now have to write a 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:

I have attempted to write this and test it, but I am now stuck also on ow I would test the 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中的Comparators,但不了解如何在测试(或print语句)中实现此功能.

The above, of course, is giving me an error. I have read up on Comparators in Lambda but do not understand how to implement this in the test(or the print statement).

感谢您的帮助/解释!P.S.如果我缺少任何信息,请让我知道,我试图尽可能地做到透彻.

Any help/explanation is appreciated!P.S. Please let me know if I am missing any information, I tried to be as thorough as possible.

推荐答案

您可以使用foldLeft定义minVal:

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));

这篇关于我如何不使用循环而仅使用foldLeft来获得minVal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 09:08