泛型 – 实现数字
发布时间: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))) } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- shell-oh-my-zsh升级后的错误:?/ .oh-my-zsh/li
- 如何掌握UNIX find命令?
- bash – 如何在数组中找到最高数字?
- angularjs $http.get让json在服务层不工作
- SuperPlan(8)TaoBao Winner - UI BootStrap - Ba
- AngularJS将requestVerificationToken传递给服务
- scala – 从构造函数参数值的映射创建类实例
- WebService认识二(使用Servlet搭建WebService服务
- angularjs – 从Angular JS $资源POST返回的值不
- 模块二;具名元组,时间,随机数,os,sys
热点阅读