【问题标题】:Scala: Implementing a subtype of Numeric[T]Scala:实现 Numeric[T] 的子类型
【发布时间】:2011-01-17 11:57:50
【问题描述】:

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

提前致谢 巨魔

【问题讨论】:

  • 您是否尝试为特定 T(例如 ComplexNumeric)或更通用的数字类型(例如 Real[T])创建 Numeric 实例?
  • 好吧,我想我想要的是一个 Numeric 的实例。我的大问题是我无法找到有关如何从新的 Numeric[T] 类型中受益的指南文档。有这样的指南吗?

标签: scala scala-2.8 generic-programming


【解决方案1】:

一个绝对没用的字符串数字:

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

【讨论】:

    【解决方案2】:

    我将Real 添加到Scalaz,实例为Real[Double]Real[Dual]

    我发现将fromDouble 设为隐式很方便

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2016-04-23
      • 1970-01-01
      相关资源
      最近更新 更多