Haskell中的Guards、模式匹配和不同的等式



回到我的动物示例:

type Pig = String
type Lion = String
type Feed = [(Char,Char)]
type Visitors = [(Char,Char)]
type Costs = (Int,Int,Int)
data AnimalHome = Farm Pig Pig Pig Feed | Zoo Lion Lion Lion Feed Visitors
orders :: Char -> AnimalHome -> Costs -> Char
orders stuff Farm p1 p2 p3 feed (cost1,cost2,cost3) = some code here

我将如何执行不同的方程式?假设p1 p2 p3被输入为"Bert"Donald"Horace",我希望它执行一个特定的等式,但如果它们被输入为"Bert"Donald"Sheila",我会希望它执行不同的等式?

原理是模式匹配。换句话说,您可以执行以下操作:

orders stuff (Farm p1 p2 p3 feed) (cost1,cost2,cost3) =
  case (p1, p2, p3) of
    ("Bert", "Donald",  "Horace") -> {- something -}
    ("Bert", "Donald",  "Sheila") -> {- something different -}
    (_,      "Abraham", _)        -> {- when p2 is "Abraham" and the others can be anything -}
    _                             -> {- this is the default case -}

在名称上进行不同的调度。正如您所看到的,下划线与任何内容都匹配,这有助于表明您已经处理了所有特殊情况,现在需要一些通用内容。

如果你愿意,你可以使用可用的简写,因为函数参数也是模式——例如,你可以这样做:

orders stuff (Farm "Bert" "Donald"  "Horace" feed) (cost1,cost2,cost3) = {- something -}
orders stuff (Farm "Bert" "Donald"  "Sheila" feed) (cost1,cost2,cost3) = {- something different -}
orders stuff (Farm p1     "Abraham" p3       feed) (cost1,cost2,cost3) = {- when p2 is "Abraham" and the others can be anything -}
orders stuff (Farm p1     p2        p3       feed) (cost1,cost2,cost3) = {- this is the default case -}

然而,在这种情况下,我建议使用case…of,因为它更容易阅读,而且当你想更改参数中的某些内容时,你不必修改每个等式。

相关内容

  • 没有找到相关文章

最新更新