0

回到我的动物示例:

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”,我希望它执行一个不同的方程方程?

4

1 回答 1

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

于 2013-11-20T11:29:06.283 回答