Skip to content

Instantly share code, notes, and snippets.

@rbuckland
Created February 24, 2015 23:28
Show Gist options
  • Save rbuckland/83b44fb3c627ccfcec0b to your computer and use it in GitHub Desktop.
Save rbuckland/83b44fb3c627ccfcec0b to your computer and use it in GitHub Desktop.
compiler error with generics
def safeSum[A: Numeric](as: Seq[A]):Option[A] =
if (as.isEmpty) None else Some(as.qsum)
def safeDiv[A: Numeric](a:Option[A], b:Option[A]):Option[Double] = (a,b) match {
case (None,_) | (_,Some(0)) | (_,None) => None
case (Some(x),Some(y)) => Some((x / y).toDouble())
}
/**
* Standard Deviation of the values.
* Square root of Variance
* Variance ( The average of the squared differences from the Mean )
* @param a Sequence of Values (Optionals)
* @param i Implict Numeric helper
* @tparam A Our Number Type
* @return
*/
def safeStdDev[A: Numeric](a: Seq[A])(implicit i: Numeric[A]):Option[A] = {
val sum = safeSum[A](a)
val len = a.size
safeDiv[A](sum,Some(i.fromInt(len))) match {
case None => None
case Some(avg:A) => {
// squared differences from the average
val devs = a.map(value => i.times( i.minus(value,avg) , i.minus(value,avg) ) )
Some(sqrt(devs.reduce((s,a) => i.plus(s,a)) / len))
}
}
}
/*
Error:(80, 25) ambiguous implicit values:
both value i of type spire.math.Numeric[A]
and value evidence$9 of type spire.math.Numeric[A]
match expected type spire.math.Numeric[A]
val sum = safeSum[A](a)
^
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment