Skip to content

Instantly share code, notes, and snippets.

@MishaelRosenthal
Created January 16, 2014 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MishaelRosenthal/8455374 to your computer and use it in GitHub Desktop.
Save MishaelRosenthal/8455374 to your computer and use it in GitHub Desktop.
Adding mean and variance to Scala collections.
package com.liveperson.predictivedialer.common.utils
/**
* Created with IntelliJ IDEA.
* User: mishaelr
* Date: 1/16/14
* Time: 3:12 PM
*/
object TraversableWithStatistics {
implicit class RichTraversable[+A](collection: Traversable[A]){
private def pow2[C, B >: C](x: C)(implicit num: Numeric[B]) = math.pow(num.toDouble(x), 2)
def mean[B >: A](implicit num: Numeric[B]) = {
num.toDouble(collection.sum[B]) / collection.size
}
def variance[B >: A](implicit num: Numeric[B]) = {
collection.map(pow2[A, B]).mean - pow2(mean[B])
}
}
}
object Example extends App {
import TraversableWithStatistics._
println((1 to 100).variance)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment