卫兵,模式匹配和Haskell中的不同方程

时间:2013-11-20 11:19:46

标签: haskell pattern-matching pattern-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”我会希望它执行不同的方程?

1 个答案:

答案 0 :(得分:1)

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

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,因为它更容易阅读,因为当您想要更改参数中的某些内容时,您不必修改每个等式。