如何实现 Numeric[T] 的子类型?我一直在寻找这方面的指南,但没有找到。子类型的示例可以是 Rational 还是 Complex?
在此先感谢 Troels
如何实现 Numeric[T] 的子类型?我一直在寻找这方面的指南,但没有找到。子类型的示例可以是 Rational 还是 Complex?
在此先感谢 Troels
一个绝对没用的字符串数字:
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
我将Real添加到 Scalaz,带有实例Real[Double]
和Real[Dual]
.
fromDouble
我发现隐式很方便