O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Counting Coins

To explore the expressive power of pattern matching, let’s write a function that will count the number of nickels, dimes, and quarters in a given collection:

 val coins = List(25, 10, 5, 10, 5, 25, 10, 5, 5, 25)

Using the traditional if-else construct, the code would look like this:

 def countCoins(coins : Seq[Int], nickels : Int = 0,
  dimes : Int = 0, quarters : Int = 0) : Map[String, Int] = {
 
  if (coins.isEmpty)
  Map("nickels" -> nickels, "dimes" -> dimes,
  "quarters" -> quarters)
  else {
  if (5 == coins.head) {
  countCoins(coins.tail, nickels + 1, dimes, quarters)
  }
  else {
  if (10 == coins.head) {
  countCoins(coins.tail, nickels, dimes + 1, quarters)
  } else {
  if (25 == coins.head) {
  countCoins(coins.tail, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required