Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching BigInts [duplicate]

Tags:

scala

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

  1. Why is the first case always matching?
  2. Is there a way to get a BigInt version of this function to work whilst sticking to pattern matching?
like image 702
Mike Hogan Avatar asked Feb 21 '26 23:02

Mike Hogan


1 Answers

You should either rename zero as Zero or use it like this:

case `zero` => 1
like image 186
senia Avatar answered Feb 24 '26 14:02

senia