Search code examples
scalamathnumerical-methodsspire

Sum or Product of Rationals with Spire (how to get a scala.Numeric)


I thought this should be straight forward:

import spire.math.Rational

val seq  = Vector(Rational(1, 4), Rational(3, 4))
val sum  = seq.sum      // missing: scala.Numeric
val prod = seq.product  // missing: scala.Numeric

I guess this is just a question of bringing the right stuff into implicit scope. But what do I import?

I can see that in order to get a RationalIsNumeric, I have to do something like this:

import spire.math.Numeric._
implicit val err = new ApproximationContext(Rational(1, 192))
implicit val num = RationalIsNumeric

But that just gives me a spire.math.Numeric. So I try with this additionally:

import spire.math.compat._

But no luck...


Solution

  • All that's needed is evidence of spire.math.compat.numeric[Rational]:

    import spire.math._
    
    val seq = Vector(Rational(1, 4), Rational(3, 4))
    implicit val num = compat.numeric[Rational]  // !
    seq.sum     // --> 1/1
    seq.product // --> 3/16