4

I have code that looks like this:

/**
  * A divisor that operates on real numbers.
  */
case class RealDivisor(divisor: Long)
  extends Divisor[Double, Double]
  with Divisor[Long, Double] // ... with Divisor[Int, Double], etc.
  {

  override def divide(dividend: Double): Double =
    if (divisor != 0) dividend / divisor.toDouble else 0

  def divide(dividend: Long): Double = divide(dividend.toDouble)

}

I'd much rather be able to do something like this:

case class RealDivisor(divisor: Long) extends Divisor[A: Numeric] {
  // ...
}

Thus I'd only need to implement the divide method once. How would I do something like this?

Ian Macalinao
  • 1,608
  • 3
  • 20
  • 30
  • `Numeric` isn't going to help very much, because it doesn't implement division. But if you follow `Numeric` as a guide, you'll find many of those instances didn't come for free. What is it that you're really looking for? The ability to divide a `Long` by other numeric types, or the ability to divide any numeric type by any numeric type? – Michael Zajac Feb 27 '17 at 20:17
  • 1
    [This question](http://stackoverflow.com/questions/40351176/generic-numeric-division) might be instructive. – jwvh Feb 27 '17 at 20:20
  • @MichaelZajac I want to be able to convert the type to `Double` so I can perform division on it; that's why I was using `Numeric`. – Ian Macalinao Feb 27 '17 at 20:27

1 Answers1

0

What you're looking for is the idea of a field.

A Field typeclass is provided by e.g. Spire.

Apocalisp
  • 34,834
  • 8
  • 106
  • 155