Created
August 1, 2014 10:06
-
-
Save ilaborie/8a7861234490809e509a to your computer and use it in GitHub Desktop.
Scala SuperNumber
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
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