Created
October 10, 2012 18:40
-
-
Save aryairani/3867578 to your computer and use it in GitHub Desktop.
Factorial in Scala
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
object Factorial { | |
implicit class LongFactorialPimp(x: Long) { | |
require(x >= 0) | |
def ! : Long = { | |
if (x < 2) 1 | |
else x * ((x-1)!) // ! has the wrong precedence compared to * :( | |
} | |
} | |
println(11!) | |
} | |
object Factorial2 { | |
import math.Ordering.Implicits._ | |
import math.Integral.Implicits._ | |
implicit def fromInt[A](x: Int)(implicit i: Integral[A]): A = i.fromInt(x) | |
implicit class IntegralFactorialPimp[A:Integral](x:A) { | |
require(x >= fromInt(0)) | |
def ! : A = { | |
if (x < 2) 1 | |
else x * ((x - fromInt(1))!) | |
} | |
} | |
println(11!) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment