Skip to content

Instantly share code, notes, and snippets.

@robcd
Created April 27, 2012 08:19
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 robcd/2507381 to your computer and use it in GitHub Desktop.
Save robcd/2507381 to your computer and use it in GitHub Desktop.
A solution to SftI Ex 21.3
trait Factorial {
def ! : BigInt
// ^ space required!
}
object Factorial {
implicit def Int2Factorial(n: Int): Factorial = new Factorial {
def ! = {
if (n < 0) throw new RuntimeException("unable to compute factorial of negative number")
@annotation.tailrec
def fact(n: Int, prevRes: BigInt): BigInt =
if (n == 0) prevRes else fact(n - 1, prevRes*n)
fact(n, 1)
}
}
}
object test extends App {
import Factorial._
assert((0!) == BigInt(1))
assert((1!) == BigInt(1))
assert((2!) == BigInt(2))
assert((3!) == BigInt(2*3))
assert((4!) == BigInt(2*3*4))
assert((5!) == BigInt(2*3*4*5))
for (n <- 0 to 5) println(n!)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment