Created
April 27, 2012 08:19
-
-
Save robcd/2507381 to your computer and use it in GitHub Desktop.
A solution to SftI Ex 21.3
This file contains hidden or 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
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