Comparison of BigInts Templates

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?
+3
source share
2 answers

You must either rename zeroas zero, or use it as follows:

case `zero` => 1
+5

``

val zero = BigInt(0)
def factorial(n:BigInt):BigInt = n match {
    case `zero` => 1
    case x => x * factorial(x - 1)
}
+3

All Articles