2010-10-27 232 views
4

我已经创建了一个可以通过什么进行参数设置一类,它可以在代码的其他地方被转换成数字斯卡拉 - 诠释对数值[INT]隐式转换

class Complex[T <% Numeric[T]] (val real : T, val imag : T) { 
    //... complex number methods ... 
} 

然后我尝试:

var myComplex = new Complex(0, 1) 

这会引发编译错误,因为(令人惊讶的是)Int和Numeric [Int]之间或Int和Integral [Int]之间没有隐式转换。

我错过了什么吗?有没有一种隐式转换,我没有看到?

在Numeric.scala中定义了一个名为IntIsIntegral的隐式对象。我用这个来创建自己的隐式转换方法的尝试:

def implicit intToNumericInt(val i : Int)(implicit n : IntIsIntegral) = n.fromInt(i) 

我很惊讶,这是必需的,无论如何,这似乎导致无限递归到.fromInt方法。我敢肯定,我错过了一些基本的东西(正如你可以说的,我是斯卡拉的新手),所以在正确的方向上我会感激一点。

从示例中可以看出,我试图获得一个可以接受和使用任何数字类型的复杂数字实现。我希望将这个贡献给scalala(线性代数)项目。接下来,我想介绍一个描述矩阵元素责任的特性(主要是+和*运算符),并将复数的支持加入到矩阵操作库中。

回答

9

您错误地使用了它。正确的用法是这样的:

class Complex[T](val real : T, val imag : T)(implicit num: Numeric[T]) { 
    import num._ // make implicit conversions available 
    //... complex number methods ... 
} 

这是相同的区别在OrderedOrdering之间。一个Ordered[T]实例可以与T进行比较,而Ordering[T]提供了一种比较几个T的方法。

+0

从我明白,则: Ť<%数值[T] 是用于将语法糖(隐式NUM:数字[T]) 但我想使用糖意味着我没有可变可以做的: import num._ //使隐式转换可用 我确实尝试过(隐含的num:Numeric [T]),但它不适用于我。明天我会报告是否导入num._帮助!谢谢。 – 2010-10-27 13:06:14

+2

@David:'T <%Numeric [T]'是添加'(隐式ev:T =>数字[T])'的语法糖,'T:Numeric [T]'是一个语法糖, (隐含的ev:数字[T])'。第一个被称为视图边界,第二个被称为类型边界。 – missingfaktor 2010-10-27 13:24:57

+2

@missingfaktor第二个称为上下文绑定,恰好用于类型模式。 – 2010-10-27 13:28:47

2

在斯卡拉2.8,它也可以写成

class Complex[T: Numeric] (val real : T, val imag : T) { 

    def +(that: Complex[T]) = { 
    val r = implicitly[Numeric[T]].plus(this.real, that.real) 
    val i = implicitly[Numeric[T]].plus(this.imag, that.imag) 
    new Complex(r, i) 
    } 

} 

这句法毫无疑问是个有点迟钝,但它可以更加可读这样的:

class Complex[T: Numeric] (val real : T, val imag : T) { 
    val num = implicitly[Numeric[T]] 

    def +(that: Complex[T]) = { 
    new Complex(num.plus(this.real, that.real), num.plus(this.imag, that.imag)) 
    } 

} 

声明class C[T: M](...) { val x = implicitly[M[T]]会似乎相当于class C[T](...)(implicit x: M[T]) { import x._,如前面解决方案的评论中所述。它不是简单的句法糖,因为它在编译过程中存在差异,例如,在第一种情况下,x是一种方法,在第二种情况下,它是一个字段。

+0

看起来这样做也可以,在这个阶段,我认为使用import num._(隐含的num:Numeric [T])更清晰,而不是使用隐含的操作,像魔术:)如果我不想从Numeric导入方法,那么语法你建议一定会更清洁。 – 2010-10-28 16:26:21

+0

我已更新答案,将您的评论纳入考虑范围。 – 2010-10-29 15:07:37