这种结构通常用于同时匹配多个变量。在顶部match
,您会看到(money, coins)
。这意味着它在 和 的对上匹配。它没有名字,因为它是完全普通的同时匹配两个值。money
coins
我无法理解对(0,_)
,(m,_)
和因为术语(_,cs)
和在代码正文中未定义。(m,cs)
m
cs
这些术语在代码中定义。case
s 定义它们。这就是匹配和解构的全部意义所在。
(money, coins) match {
case (0, _) => 1 // If money == 0, then coins is ignored and we return 1
case (m, _) if m < 0 => 0 // m = money, coins is ignored. If m < 0, return 0
case (_, cs) if cs.isEmpty => 0 // money is ignored, cs = coins.
// If we have no coins, return 0.
case (m, cs) => countChange(m - cs.head, cs) + countChange(m, cs.tail)
// Otherwise, m = money, cs = coins. Recurse down the list with
// countChange(money - coins.head, coins) + countChange(money, coins.tail)
}
元组的原因(money, coins)
是因为这些模式同时依赖于 money
和coins
。你要么需要嵌套match
s (丑陋的),要么做更丑陋的布尔逻辑来复制这些语义。