Guest User

Generic numerical operations.

a guest
Apr 13th, 2017
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.35 KB | None | 0 0
  1. abstract class NumericCombine[A: Numeric, B: Numeric] {
  2.     type AB <: AnyVal
  3.  
  4.     def fromA(x: A): AB
  5.     def fromB(y: B): AB
  6.     val num: Numeric[AB]
  7.  
  8.     def plus(x: A, y: B): AB = num.plus(fromA(x), fromB(y))
  9.     def minus(x: A, y: B): AB = num.minus(fromA(x), fromB(y))
  10.     def times(x: A, y: B): AB = num.times(fromA(x), fromB(y))
  11. }
  12.  
  13. abstract class NumericCombineImpl[A: Numeric, B: Numeric, R <: AnyVal]
  14. (implicit override val num: Numeric[R])
  15.     extends NumericCombine[A, B] {
  16.     type AB = R
  17. }
  18.  
  19. abstract class NumericCombineImpl2[A<: AnyVal]
  20.         (implicit override val num: Numeric[A])
  21.             extends NumericCombine[A, A] {
  22.             type AB = A
  23.             override def fromA(x: A): A = x
  24.             override def fromB(y: A): A = y
  25. }
  26.  
  27. object implicits {
  28.  
  29.     implicit object IntFloat extends NumericCombineImpl[Int, Float, Float] {
  30.         override def fromA(x: Int): AB = x.toFloat
  31.         override def fromB(y: Float): AB = y
  32.     }
  33.  
  34.     implicit object FloatInt extends NumericCombineImpl[Float, Int, Float] {
  35.         override def fromA(x: Float): Float = x
  36.         override def fromB(y: Int): Float = y.toFloat
  37.     }
  38.  
  39.     implicit object IntInt extends NumericCombineImpl2[Int]
  40. }
  41.  
  42. object NumericOps{
  43.     def plus[A: Numeric, B: Numeric](x: A, y: B)(implicit ev: NumericCombine[A, B])
  44.     : ev.AB = ev.plus(x, y)
  45. }
Advertisement
Add Comment
Please, Sign In to add comment