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 using BigInt so that it works for numbers of any size, such as
val zero = BigInt(0)
def factorial(n:BigInt):BigInt = n match {
case zero => 1
case x => x * factorial(x - 1)
}
Each factorial call returns from 1 regardless of the value of n. I assumed that this is because the first case always coincides, and I proved that this is so by changing it to
case zero => 22
and confirming that 22 was returned for each entry.
So my two questions:
- Why is the first case always the same?
- Is there a way to get a version of this BigInt function to work by sticking to pattern matching?
source
share