Scala:实现Numeric的子类型[T]

时间:2010-02-16 17:04:24

标签: scala scala-2.8 generic-programming

如何实现Numeric [T]的子类型? 我一直在寻找这方面的指南,但没有找到任何。 子类型的示例可以是Rational还是Complex?

提前致谢 特勒尔斯

2 个答案:

答案 0 :(得分: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 :(得分:1)

我向Scalaz添加了Real,其中包含Real[Double]Real[Dual]个实例。

我发现fromDouble隐式

很方便