我正在尝试从“Scala编程 - 第二版”一书中理解下面的类中的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)
}
答案 0 :(得分:4)
这两个表达式是Rational
构造函数的参数,因此它们分别是private val
s n
和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