Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Real Interval, Int Interval

How do I define a boiler-plate-eliminating superclass of these two simple Interval classes?

class IntInterval(val from: Int, val to: Int) { 
    def mid: Double = (from+to)/2.0 
    def union(other: IntInterval) = IntInterval(from min other.from, to max other.to)
}

class DoubleInterval(val from: Double, val to: Double) { 
    def mid: Double = (from+to)/2.0 
    def union(other: DoubleInterval) = DoubleInterval(from min other.from, to max other.to)
}

I tried

class Interval[T <: Number[T]] (val from: T, val to: T) { 
    def mid: Double = (from.doubleValue+to.doubleValue)/2.0 
    def union(other: IntInterval) = Interval(from min other.from, to max other.to)
}

but the min and max did not compile in the union method (since Number[T] does not have min/max).

Can you provide an elegant superclass which deals with both the mid and union methods in a neat, code-once-and-only-once boilerplate-avoiding way?

like image 427
Perfect Tiling Avatar asked Oct 07 '22 20:10

Perfect Tiling


1 Answers

I think you are looking for the scala.math.Numeric typeclass:

class Interval[T] (val from: T, val to: T)(implicit num: Numeric[T]) { 
  import num.{mkNumericOps, mkOrderingOps}

  def mid: Double  = (from.toDouble + to.toDouble)/2.0 
  def union(other: Interval[T]) = new Interval(from min other.from, to max other.to)
}
like image 125
soc Avatar answered Oct 10 '22 22:10

soc