Created
April 27, 2013 15:24
-
-
Save jamesthompson/5473476 to your computer and use it in GitHub Desktop.
Normalizer. Takes any TraversableLike collection of Numeric values and returns those values normalized as Double between 0 and 1.
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
import scala.collection.generic.CanBuildFrom | |
import scala.collection.TraversableLike | |
implicit class Normalizer[N:Numeric, M[+_]](xs:M[N]) { | |
def normalize(implicit bf: CanBuildFrom[M[N], Double, M[Double]], | |
ev: M[N] => TraversableLike[N, M[N]], | |
eb: M[Double] => TraversableLike[Double, M[Double]]) = { | |
val n = implicitly[Numeric[N]] | |
val mind = n.toDouble(xs.min) | |
val maxd = n.toDouble(xs.max) | |
xs.map(v => (n.toDouble(v) - mind) * (1 / (maxd - mind))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could do Spire Rationals thus : (n.b. imports for Rationals are required)
import scala.collection.generic.CanBuildFrom
import scala.collection.TraversableLike
implicit class NormalizeRationalM[+_] {
def normalize(implicit bf: CanBuildFrom[M[Rational], Rational, M[Rational]],
ev: M[Rational] => TraversableLike[Rational, M[Rational]]) = {
val minr = xs.min
val maxr = xs.max
xs.map(v => (v - minr) * (r"1" / (maxr - minr)))
}
}