我如何不使用循环而仅使用foldLeft来获得minPos?

问题描述 投票:0回答:1

我一直在努力解决该问题。目的是找到没有循环的Iterable(l)最小值的位置。这里有一个类似的问题:How would I get the minVal without a loop and using only foldLeft?但这可以简单地使用lambda。在这种情况下,我需要将实现BiFunction的类作为第三个参数传递给foldLeft或foldRight调用。您将如何解决?我开始制作一个实现BiFunction的新类,但对如何确定最小值在l中的位置一无所知。

static <U,V> V foldLeft(V e, Iterable<U>l, BiFunction<V,U,V> f){
    //BiFunction takes a U and V and returns a V
    V ret = e;

    for(U i : l) {
        ret = f.apply(ret, i);
    }

    return ret;
}

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
}

static <U extends Comparable<U>> int minPos(Iterable<U> l){
    // write using fold.  No other loops permitted.
    int value = 0;


    return value;
}

更新:我知道了

class FindMinPos<U extends Comparable<U>> implements BiFunction<U, U, U> {

    public Iterable<U> l;
    public ArrayList<U> a = new ArrayList<U>();
    public int minPos;

    public FindMinPos(Iterable<U> l) {
        this.l = l;
        for(U i : l) {
            a.add(i);
        }
    }

    @Override
    public U apply(U u, U u2) {
        U minVal = u != null && u.compareTo(u2) <= 0 ? u : u2;
        minPos = a.indexOf(minVal);

        return minVal;
    }
}

static <U extends Comparable<U>> int minPos(Iterable<U> l){
    // write using fold.  No other loops permitted.
    int minPos = 0;

    FindMinPos<U> f = new FindMinPos<U>(l);
    U minValue = foldLeft(l.iterator().next(), l, f);
    minPos = f.minPos;

    return minPos;
}
java oop functional-programming fold
1个回答
0
投票

如果您将minPos()的返回类型固定为与参数一致,则可以使用如下lambda表达式来实现:

static <U extends Comparable<U>> U minPos(Iterable<U> coll) {
    return foldLeft((U) null, coll, (a, b) -> a != null && a.compareTo(b) <= 0 ? a : b);
}
© www.soinside.com 2019 - 2024. All rights reserved.