【问题标题】:Unsure how a method works within a scala class不确定方法在 scala 类中如何工作
【发布时间】:2012-09-13 21:49:04
【问题描述】:

我正在尝试理解以下类中的 add 方法,该方法取自“Scala 编程 - 第二版”一书。 它是否正确 : 'add' 采用的方法定义了一个 Rational 类型的运算符。我不知道新 Rational 中发生了什么:

numer * that.denom + that.numer * denom,
denom * that.denom

numer & denom 在这里是如何分配的? , 为什么每个表达式用逗号分隔? 全班:

class Rational(n: Int , d: Int) {

  require(d != 0)

  private val g = gcd(n.abs, d.abs)
  val numer = n / g
  val denom = d/ g

  def this(n: Int) = this(n, 1)

  def add(that: Rational): Rational = 
    new Rational(
        numer * that.denom + that.numer * denom,
        denom * that.denom
        )

  override def toString = numer +"/" + denom

  private def gcd(a: Int, b: Int): Int = 
    if(b == 0) a else gcd(b, a % b)
}

【问题讨论】:

    标签: scala


    【解决方案1】:

    这两个表达式是Rational 构造函数的参数,因此它们将分别是private vals nd。例如

    class C(a: Int, b: Int)
    val c1 = new C(1, 2) // here 1, 2 is like the two expressions you mention
    

    add 方法实现有理数加法:

     a     c     a*d     c*b     a*d + c*b
    --- + --- = ----- + ----- = -----------
     b     d     b*d     b*d        b*d
    

    在哪里

     a = numer
     b = denom
     c = that.numer
     d = that.denom
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 2015-05-03
      • 2012-12-31
      • 2013-06-06
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      相关资源
      最近更新 更多