6

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

0__
  • 66,707
  • 21
  • 171
  • 266
  • OT: what are you using spire for? – Edmondo May 06 '13 at 11:34
  • 1
    I'm doing rhythmical (musical) calculations. Musical durations are usually expressed as rationals, so you need to be able to mangle those :) E.g. given a rhythmic cell with relative durations of 3, 2, 1 and a total duration of 1/2, calculate the individual durations, find some stretch factors which lead to small denominators etc. – 0__ May 06 '13 at 11:36

2 Answers2

8

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__
  • 66,707
  • 21
  • 171
  • 266
7

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.

d_m
  • 176
  • 1
  • 2