我对Scala很新.我想写几个数学对象(Complex,Polynomial等),这些对象在某些操作(+, - ,*)下是封闭的,它们可以在泛型中使用,并且可以使用隐式强制转换.
我似乎已经解决了第一点.
trait GroupUnderAddition[T] {
def + (t : T) : T
}
case class Real(d : Double) extends GroupUnderAddition[Real] {
def + (r : Real) = Real(d + r.d)
}
case class Complex(re : Double, im : Double) extends GroupUnderAddition[Complex] {
def + (c : Complex) = Complex(re + c.re, im + c.im)
}
object Test {
implicit def real_to_complex(r : Real) = Complex(r.d, 0)
def test[G <: GroupUnderAddition[G]](a : G, b : G) = a + b
def main(args : Array[String]) {
println(test(Real(5), Real(2)))
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我该怎么写test()呢
test(Real(5), Complex(2, 1))
Run Code Online (Sandbox Code Playgroud)
返回Complex(7,1)?
主要思想是所有 GroupUnderAddition 都不兼容,因此当您似乎想要使用复杂代数时,我建议构建一个包括 GoupUnderAddition 的超类。但是,不建议将其设为案例类(如果您有case class扩展 a ,请参阅警告case class)
trait GroupUnderAddition[T] {
def + (t : T) : T
}
class ComplexAlgebra(_re:Double, _im:Double) extends(GroupUnderAddition[ComplexAlgebra]) {
val re = _re
val im = _im
def + (c : ComplexAlgebra) = new ComplexAlgebra(re + c.re, im + c.im)
}
case class Real(d : Double) extends ComplexAlgebra(d, 0)
case class Complex(real : Double, imaginary : Double) extends ComplexAlgebra(real,imaginary)
object Test {
def test(a : ComplexAlgebra, b : ComplexAlgebra) = a + b
def main(args : Array[String]) {
println(test(Real(5), Real(2)))
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
218 次 |
| 最近记录: |