7

How does one go about implementing a subtype of Numeric[T]? I have been looking for at guide on this but haven't found any. Example of subtypes could be Rational or Complex?

Thanks in advance Troels

Thomas Jung
  • 32,428
  • 9
  • 84
  • 114
Troels Blum
  • 823
  • 8
  • 17
  • Are you trying to create an instance of Numeric for a specific T, (e.g. ComplexNumeric), or a more general numeric type, (e.g. Real[T])? – retronym Feb 17 '10 at 07:12
  • Well I guess what I want is an instance of Numeric. My big problem is that I haven't been able to find a guide documentation on how to benefit from the new Numeric[T] type. Does such a guide exist? – Troels Blum Feb 17 '10 at 10:39

2 Answers2

16

An absolutely useless String Numeric:

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
Thomas Jung
  • 32,428
  • 9
  • 84
  • 114
1

I added Real to Scalaz, with instances Real[Double] and Real[Dual].

I found it convenient to make fromDouble implicit

retronym
  • 54,768
  • 12
  • 155
  • 168