【问题标题】:type mismatch in scala when using reduce使用reduce时scala中的类型不匹配
【发布时间】:2018-10-20 23:48:11
【问题描述】:

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

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)
                            ^

【问题讨论】:

    标签: scala reduce type-mismatch


    【解决方案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)
    }
    

    【讨论】:

      【解决方案2】:

      如果你想使用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,因此它的效率可能会稍低。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-27
        • 2011-10-19
        • 2017-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-15
        相关资源
        最近更新 更多