2010-02-16 35 views
7

如何实现数字[T]的子类型? 我一直在寻找指导,但没有找到任何。 子类型的例子可能是理性的还是复杂的?Scala:实现数字的子类型[T]

在此先感谢 特勒尔斯

+0

你们是不是要为特定的T,(例如ComplexNumeric),或更一般的数字类型,(例如房地产[T])建立数字的实例? – retronym

+0

嗯,我想我想要的是一个数字的实例。我的大问题是,我无法找到关于如何从新的Numeric [T]类型获益的指南文档。这样的指南是否存在? –

回答

16

一个绝对无用串数字:

trait StringIsNumeric extends Numeric[String] { 
    def plus(x: String, y: String): String = "%s+%s" format (x, y) 
    def minus(x: String, y: String): String = "%s-%s" format (x) 
    def times(x: String, y: String): String = "%s*%s" format (x, y) 
    def quot(x: String, y: String): String = "%s/%s" format (x, y) 
    def rem(x: String, y: String): String = "%s%%s" format (x, y) 
    def negate(x: String): String = "-%s" format (x) 
    def fromInt(x: Int): String = x.toString 
    def toInt(x: String): Int = 0 
    def toLong(x: String): Long = 0L 
    def toFloat(x: String): Float = 0.0f 
    def toDouble(x: String): Double = 0.0 
} 
implicit object StringIsNumeric extends StringIsNumeric with Ordering.StringOrdering 


def x[T: Numeric](t1 : T, t2 : T) = { 
    val n = implicitly[Numeric[T]] 
    import n._ 
    t1 * t2 
} 
scala> x("a","b") 
res0: java.lang.String = a*b 
1

我加Real到Scalaz,用实例Real[Double]Real[Dual]

我认为很方便,使fromDouble隐含