Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 738
0__ Avatar asked May 06 '13 10:05

0__


People also ask

How to sum all the elements of a Scala list?

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.

How to implement recursive sum function in Scala?

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:

What happens if the list is not empty in Scala?

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

What is the sum of two rational numbers?

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.


1 Answers

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
like image 137
0__ Avatar answered Nov 15 '22 08:11

0__