July 2017
Intermediate to advanced
284 pages
6h 45m
English
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, ... |
Read now
Unlock full access