简体   繁体   English

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

[英]Guards, Pattern Matching and different equations in Haskell

Getting back to my animals example: 回到我的动物的例子:

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

How would I execute different equations? 我将如何执行不同的方程式? Say if p1 p2 p3 were entered as "Bert" "Donald" "Horace" I would want it to execute one specific equation, but if they were entered as "Bert" "Donald" "Sheila" I would want it to execute a different equation? 假设如果将p1 p2 p3输入为“ Bert”,“ Donald”,“ Horace”,我希望它执行一个特定的方程式,但是如果将它们输入为“ Bert”,“ Donald”,“ Sheila”,我希望它执行一个不同的方程式方程?

The principle is pattern matching. 原理是模式匹配。 In other words, you can do the following: 换句话说,您可以执行以下操作:

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 -}

to dispatch differently on the names. 以不同的方式分配名称。 As you see, an underscore matches on anything and is useful to indicate that you have handled all your special cases and now need something general. 如您所见,下划线可以匹配任何内容,对于表明您已经处理了所有特殊情况,现在需要通用内容很有用。

If you want to, you can employ the shorthand available due to the fact that function parameters also are patterns – eg you can do this: 如果需要,可以使用可用的速记,因为函数参数也是模式-例如,您可以执行以下操作:

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 -}

In this case, however, I recommend the case…of , both because it is easier to read and because when you want to change something in the arguments you don't have to modify every equation. 但是,在这种情况下,我建议使用case…ofcase…of ,这既因为它更易于阅读,又因为当您想更改参数中的某些内容时,不必修改每个方程式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM