使用reduce时scala中的类型不匹配

时间:2018-05-10 16:27:50

标签: scala reduce type-mismatch

有人能帮我理解下面的代码有什么问题吗?

case class Point(x: Double, y: Double)

def centroid(points: IndexedSeq[Point]): Point = {
  val x = points.reduce(_.x + _.x)
  val y = points.reduce(_.y + _.y)
  val len = points.length
  Point(x/len, y/len)
}

我在运行时遇到错误:

Error:(10, 30) type mismatch;
 found   : Double
 required: A$A145.this.Point
  val x = points.reduce(_.x + _.x)
                            ^

2 个答案:

答案 0 :(得分:1)

在这种情况下,

reduce采用(Point, Point) => Point类型的函数并返回Point

计算质心的一种方法:

case class Point(x: Double, y: Double)

def centroid(points: IndexedSeq[Point]): Point = {
  val x = points.map(_.x).sum
  val y = points.map(_.y).sum
  val len = points.length
  Point(x/len, y/len)
}

答案 1 :(得分:1)

如果你想使用reduce,你需要像这样一次性减少xy

def centroid(points: IndexedSeq[Point]): Point = {
  val p = points.reduce( (s, p) => Point(s.x + p.x, s.y + p.y) )
  val len = points.length

  Point(p.x/len, p.y/len)
}

如果您想独立计算xy,请使用foldLeft而不是reduce这样

def centroid(points: IndexedSeq[Point]): Point = {
  val x = points.foldLeft(0.0)(_ + _.x)
  val y = points.foldLeft(0.0)(_ + _.y)
  val len = points.length

  Point(x/len, y/len)
}

这可能更清楚,但会处理points两次,因此效率可能稍低。