Skip to content

Instantly share code, notes, and snippets.

@aryairani
Created October 10, 2012 18:40
Show Gist options
  • Save aryairani/3867578 to your computer and use it in GitHub Desktop.
Save aryairani/3867578 to your computer and use it in GitHub Desktop.
Factorial in Scala
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