Skip to content

Instantly share code, notes, and snippets.

@jamesthompson
Created April 27, 2013 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesthompson/5473476 to your computer and use it in GitHub Desktop.
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.
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)))
}
}
@jamesthompson
Copy link
Author

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)))
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment