これは、コインのリストを再帰的にトラバースするために使用されているパターン マッチングの例です。これは、同じコードをコメントで書き直したものです。知っておくべき重要なことは、各case
ステートメントがタプルの可能なパターンと一致しており、タプルの_
一部を無視するために使用されていることです。
def countChange(money: Int, coins: List[Int]): Int = {
// Construct a tuple for pattern matching on
val tuple: (Int, List[Int]) = (money, coins)
tuple match {
// Check to see if money == 0
case (0, _) => 1
// m represents money, use a guard to check if m is negative
case (m, _) if m < 0 => 0
// cs represents coins, use a guard statement check for empty list
case (_, cs) if cs.isEmpty => 0
// Recursive step. Since the patterns are tried in order, we
// now know that if we make it to here m (money) is non-zero
// and non-negative, and we know that cs (coins) is a non-empty
// list. Now we can call the recursive function safely on
// the head of the list
case (m, cs) => countChange(m - cs.head, cs) + countChange(m, cs.tail)
}
}