This factorial implementation works for numbers up to a certain size:
def factorial(n:Int):Int = n match {
case 0 => 1
case x => x * factorial(x - 1)
}
I tried to use BigInt to make it work for numbers of any size like this
val zero = BigInt(0)
def factorial(n:BigInt):BigInt = n match {
case zero => 1
case x => x * factorial(x - 1)
}
Every call to factorial comes back with 1 regardless of the value of n. I assumed this is because the first case is always matching, and proved it is so by changing it to
case zero => 22
and verifying that 22 was returned for every input.
So my two questions are
You should either rename zero as Zero or use it like this:
case `zero` => 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With