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...
Scala List sum () method with example. Last Updated : 26 Jul, 2019. The sum () method is utilized to add all the elements of the stated list. Method Definition: def sum (num: math.Numeric [B]): B. Return Type: It returns the sum of all the elements of the list.
Recursive Scala functions are often implemented using match expressions. Using (a) that information and (b) remembering that an empty list contains only the Nil element, you can start writing the body of the sum function like this:
That case expression is a Scala/FP implementation of the first sentence, so let’s move on to the second sentence. The second sentence says, “If the list is not empty, the result of the algorithm is the combination of (a) the value of its head element, and (b) the sum of its tail elements.”
You have the ratio of two integers. So the sum of two rational numbers is going to give you another. So this one right over here was rational, and this one is right over here is rational. So you take the product of two rational numbers, you get a rational number.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With