【问题标题】:Calculation Distance Between Points计算点之间的距离
【发布时间】:2014-11-29 02:17:00
【问题描述】:

我正在尝试使用 Scala 类计算两点之间的距离。但它给出了一个错误提示

类型不匹配; found : other.type (基础类型 Point) required: ?{def x: ?} 注意隐式转换不是 适用,因为它们是模棱两可的:两种方法 any2Ensuring in [A](x:A)Ensuring[A] 类型的对象 Predef 和方法 any2ArrowAssoc 在 [A](x:A)ArrowAssoc[A] 类型的对象 Predef 中是可能的 从 other.type 到 ?{def x: ?}

的转换函数
class Point(x: Double, y: Double) {
  override def toString = "(" + x + "," + y + ")"


  def distance(other: Point): Double = {
    sqrt((this.x - other.x)^2 + (this.y-other.y)^2 )
  }
}

【问题讨论】:

    标签: scala


    【解决方案1】:

    您也可以使用math 模块中的内置hypot 函数(如“hypotenuse”)来计算两点之间的距离:

    case class Point(x: Double, y: Double)
    
    def distance(a: Point, b: Point): Double =
      math.hypot(a.x - b.x, a.y - b.y)
    

    【讨论】:

      【解决方案2】:

      以下对我来说编译得非常好:

      import math.{ sqrt, pow }
      
      class Point(val x: Double, val y: Double) {
        override def toString = s"($x,$y)"
      
        def distance(other: Point): Double =
          sqrt(pow(x - other.x, 2) + pow(y - other.y, 2))
      }
      

      我还想指出,您的 Point 作为案例类更有意义:

      case class Point(x: Double, y: Double) { // `val` not needed
        def distance(other: Point): Double =
          sqrt(pow(x - other.x, 2) + pow(y - other.y, 2))
      }
      
      val pt1 = Point(1.1, 2.2) // no 'new' needed
      println(pt1)  // prints Point(1.1,2,2); toString is auto-generated
      val pt2 = Point(1.1, 2.2)
      println(pt1 == pt2) // == comes free
      pt1.copy(y = 9.9) // returns a new and altered copy of pt1 without modifying pt1
      

      【讨论】:

        猜你喜欢
        • 2014-02-28
        • 2010-10-30
        • 1970-01-01
        • 2011-04-23
        • 2014-11-14
        • 2021-02-05
        相关资源
        最近更新 更多