generics - 实现数字

标签 generics scala

我对 Scala 很陌生。我想编写几个数学对象(复数、多项式等),它们在某些操作(+、-、*)下关闭,它们可以在泛型中使用,并且可以使用隐式强制转换。

我似乎已经解决了第一点。

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)))
  }
}

现在,我该如何编写 test() 以便
test(Real(5), Complex(2, 1))

返回 Complex(7, 1) ?

最佳答案

主要思想是所有 GroupUnderAddition 都不兼容,因此您似乎想要使用复杂的代数,我建议构建一个包含 GoupUnderAddition 的父类(super class)。但是,不建议将其设为 case 类(如果您有 case class 扩展 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)))
  }
}

关于generics - 实现数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9248209/

相关文章:

generics - Rust 泛型局部变量

java - 将泛型类型转换为子类型

c# - 通用策略模式

java - 在 GenericObjectPool 中创建对象

java - 用泛型实现父子关系

scala - 带有可变参数的 scala 中的构造函数

scala - 覆盖 Pair 的 equals() 方法

scala - Scala 中的广义结构类型一致性

scala - 使用 IntelliJ 13 和 SBT 0.13 玩 2.2.2 无法运行 - 未检测到主类

Scala奇怪的 map 函数行为