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

599 Views Asked by At

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...

2

There are 2 best solutions below

0
On BEST ANSWER

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
0
On

It's also worth noting that Spire provides its own versions of sum and product that it calls qsum and qproduct:

import spire.implicits._
import spire.math._

Vector(Rational(1,3), Rational(1,2)).qsum // 5/6

Spire prefixes all its collection methods with q to avoid conflicting with Scala's built-in methods. Here's a (possibly incomplete) list:

  • qsum
  • qproduct
  • qnorm
  • qmin
  • qmax
  • qmean
  • qsorted
  • qsortedBy
  • qsortedWith
  • qselected
  • qshuffled
  • qsampled
  • qchoose

Sorry I came a bit late to this, I'm new to StackOverflow.