Skip to content

Instantly share code, notes, and snippets.

@ilaborie
Created August 1, 2014 10:06
Show Gist options
  • Save ilaborie/8a7861234490809e509a to your computer and use it in GitHub Desktop.
Save ilaborie/8a7861234490809e509a to your computer and use it in GitHub Desktop.
Scala SuperNumber
implicit class SuperNumber[A](i: A)(implicit integral: Integral[A]) {
import integral._
import Numeric.Implicits._
def squared: A = i * i
def pow(m: Int) = math.pow(i.toDouble(), m)
def **(m: Int) = pow(m)
def sqrt = math.sqrt(i.toDouble())
def isEven = dividesBy(2)
def isOdd = !isEven
def dividesBy(m: Int) = {
i match {
case n @ (_: Int | _: Long) => n.toLong() % m == 0
case other => {
val asDouble = other.toDouble()
val asLong = other.toLong()
if (asDouble == asLong) {
asLong % m == 0
} else {
false
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment