【问题标题】:How would I get the minVal without a loop and using only foldLeft?如何在没有循环且仅使用 foldLeft 的情况下获得 minVal?
【发布时间】: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


    【解决方案1】:

    您可以使用foldLeftminVal 定义为:

    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&lt;Integer 调用它:

    List<Integer> numList = List.of(5, 10, 15, 20, 22, 1);
    System.out.println(minVal(numList, Integer::compare));
    

    【讨论】:

    • 谢谢!我可以通过添加“Integer::compare”来测试我的方法。然后你的 foldLeft 让我更了解了这一点!我还有一个问题,如果我想获得最大值,我该如何翻转这个?
    • @QWERTY 更改三元运算符中的符号(即(u, u2) -&gt; c.compare(u, u2) &gt; 0 ? u : u2)应该足以获得最大值而不是最小值。
    • 我明白了,但我想知道是否有一种方法可以仅用一行来计算最小值和最大值?下一个测试要做的是// (6) Use minVal to calculate the maximum of a List of Integers。再次感谢您的帮助!
    • @QWERTY 哦,这样,是的,您可以反转传递给minValComparator,这样System.out.println(minVal(numList, Comparator.&lt;Integer&gt;comparingInt(x -&gt; x).reversed())); 将使用现有数据打印22
    • 老兄,非常感谢你。我开始阅读有关比较器的更多信息,您的解决方案确实对此有所帮助。我真的很感谢所有的帮助!
    猜你喜欢
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2011-01-15
    相关资源
    最近更新 更多