1

ここでこのコードを理解しようとしています

  def countChange(money: Int, coins: List[Int]): Int = (money, coins) match {
     case (0, _) => 1
     case (m, _) if m < 0 => 0
     case (_, cs)  if cs.isEmpty => 0
     case (m, cs) => countChange(m - cs.head, cs) + countChange(m, cs.tail) 
  }
}

(0,_)ここで、 、(m,_)(_,cs)およびのペアを理解できません。(m,cs)これは、用語mおよびcsがコードの本文で定義されていないためです。

リストをトラバースする際のこの構造は何と呼ばれますか? いくつかの一致するパターンのペア?

4

3 に答える 3

2

これは、コインのリストを再帰的にトラバースするために使用されているパターン マッチングの例です。これは、同じコードをコメントで書き直したものです。知っておくべき重要なことは、各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)
  }

}
于 2017-09-03T14:54:49.060 に答える