2010-02-16 56 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隱含