2

本「ProgramminginScala-SecondEdition」から抜粋した以下のクラスのaddメソッドを理解しようとしています。これは正しいですか:'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)
}
4

1 に答える 1

4

その2つの式はRationalコンストラクターへの引数であるため、それぞれprivate valsnとになりdます。例えば

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
于 2012-09-13T21:56:27.550 に答える