Amount or product of rationals with Spire (how to get scala.Numeric)

I thought it should be straight:

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 assume that this is just a matter of bringing the correct material to an implicit volume. But what should I import?

I see that in order to get RationalIsNumeric I need 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 spire.math.Numeric . Therefore, I try with this additionally:

 import spire.math.compat._ 

But no luck ...

+6
source share
2 answers

All that is needed is evidenced by 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 
+8
source

It is also worth noting that Spire provides its own versions of sum and product , which it calls qsum and qproduct :

 import spire.implicits._ import spire.math._ Vector(Rational(1,3), Rational(1,2)).qsum // 5/6 

Spire prefix all its collection methods with q to avoid conflict 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'm a little late, I'm new to StackOverflow.

+6
source

Source: https://habr.com/ru/post/944358/


All Articles