加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

泛型 – 实现数字

发布时间:2020-12-16 19:16:20 所属栏目:安全 来源:网络整理
导读:我对 Scala很新.我想编写几个数学对象(Complex,Polynomial等),这些对象在某些操作(,–,*)下是封闭的,它们可以在泛型中使用,并且可以使用隐式强制转换. 我似乎已经解决了第一点. trait GroupUnderAddition[T] { def + (t : T) : T}case class Real(d : Double
我对 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)))
  }
}

现在,我该怎么写test()呢

test(Real(5),Complex(2,1))

返回Complex(7,1)?

解决方法

主要的想法是所有GroupUnderAddition都不兼容,因此你似乎想要使用复杂的代数,我建议建立一个包含GoupUnderAddition的超类.但是,不建议将其作为案例类(如果您有一个扩展案例类的案例类,请参阅警告)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读