Scala Cookbook: Pattern matching on BigInt

Let’s take the factorial algorithm as an example.

[scala]
def factorial(x: BigInt): BigInt = {
if (x == 0) 1 else x * factorial(x – 1)
}
[/scala]

One might expect to convert this into a pattern matched equivalent as follows.

[scala]
def factorial(x: BigInt): BigInt = x match {
case 0 => 1
case _ => x * factorial(x – 1)
}
[/scala]

In fact this will give you the error below.

type mismatch;  found   : Int(0)  required: BigInt	Factorial.scala

The reason is that BigInt is not a case class and does not have an unapply() method in its companion object.

However a small modification allows the pattern matching implementation to succeed.

[scala]
def factorial(x: BigInt): BigInt = x match {
case y: BigInt if y == 0 => 1
case _ => x * factorial(x – 1)
}
[/scala]

Arguably the if/else equivalent is simpler but if you always use pattern matching you’ll want this version.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s