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, ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.