使用reduce时scala中的类型不匹配
type mismatch in scala when using reduce
任何人都可以帮助我理解下面的代码有什么问题吗?
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)
^
reduce
,在这种情况下,采用 (Point, Point) => Point
和 returns 类型的函数 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)
}
如果您想使用 reduce
,您需要像这样一次性减少 x
和 y
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)
}
如果你想独立计算 x
和 y
然后使用 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
两次,因此效率可能略低。
任何人都可以帮助我理解下面的代码有什么问题吗?
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)
^
reduce
,在这种情况下,采用 (Point, Point) => Point
和 returns 类型的函数 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)
}
如果您想使用 reduce
,您需要像这样一次性减少 x
和 y
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)
}
如果你想独立计算 x
和 y
然后使用 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
两次,因此效率可能略低。