Created
January 16, 2014 13:57
-
-
Save MishaelRosenthal/8455374 to your computer and use it in GitHub Desktop.
Adding mean and variance to Scala collections.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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