【问题标题】:How would I get the minPos without a loop and using only foldLeft?如何在没有循环且仅使用 foldLeft 的情况下获得 minPos?
【发布时间】:2020-05-15 15:39:25
【问题描述】:

我一直在想如何解决这个问题。目标是找到没有循环的 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;
}

【问题讨论】:

  • 你不相信lambda可以实现BiFunction吗?
  • 我知道它可以是一个 lambda。只是不确定是否可以通过将 lambda 作为第三个参数传递给 minPos 来获得此方法的所需功能?
  • 您无法实现 minPos,因为您会为 List&lt;String&gt;Set&lt;Point2D&gt; 返回什么 int 值作为最小值?

标签: java oop functional-programming fold


【解决方案1】:

如果您将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);
}

【讨论】:

  • 很遗憾,我们无法更改此作业的签名,因此我无法随意更改。
  • @laraveldev17 那么你如何从U 中获得int 值,因为U 几乎可以是任何东西?
猜你喜欢
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 2011-01-15
相关资源
最近更新 更多