【问题标题】:ReduceLeft with Vector of pairs?ReduceLeft 与向量对?
【发布时间】:2023-03-10 12:07:01
【问题描述】:

我有一个向量对

Vector((9,1), (16,2), (21,3), (24,4), (25,5), (24,6), (21,7), (16,8), (9,9), (0,10))

我想返回具有最大第一个元素的对。 我试过这样做:

data reduceLeft[(Int, Int)]((y:(Int, Int),z:(Int,Int))=>y._1 max z._1)

data reduceLeft((y:(Int, Int),z:(Int,Int))=>y._1 max z._1)

但存在类型不匹配错误,我无法理解这段代码有什么问题。

【问题讨论】:

标签: scala


【解决方案1】:

为什么要使用 reduceLeft ? 只是默认的 max 方法效果很好

scala> val v = Vector((9,1), (16,2), (21,3), (24,4), (25,5), (24,6), (21,7), (16,8), (9,9), (0,10))
v: scala.collection.immutable.Vector[(Int, Int)] = Vector((9,1), (16,2), (21,3), (24,4), (25,5), (24,6), (21,7), (16,8), (9,9), (0,10))

scala> v.max 
res1: (Int, Int) = (25,5)

如果你想要 reduceLeft 代替:

v.reduceLeft( (x, y) => if (x._1 >= y._1) x else y )

你的错误是你必须返回一个元组,而不是一个 int

y._1 max z._1

这里的 max 函数对两个 int 返回一个 int。

【讨论】:

    【解决方案2】:

    max 在这个例子中效果很好。但是,如果您想知道如何使用 reduceLeft 来做到这一点,那就是:

    val v = Vector((9,1), (16,2), (21,3), (24,4), (25,5), (24,6), (21,7), (16,8), (9,9), (0,10))
    v.reduceLeft( ( x:(Int, Int), y:(Int,Int) ) => if(y._1 > x._1) y else x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-01
      • 2011-02-11
      • 2018-06-27
      • 1970-01-01
      • 2021-07-03
      • 2015-04-22
      • 2011-09-11
      • 1970-01-01
      相关资源
      最近更新 更多