2013-11-20 56 views
0

再回到我的動物,例如不同的方程式:逆天,模式匹配,並在Haskell

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

原理是模式匹配。換句話說,您可以執行以下操作:

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,一方面是因爲它更容易閱讀和因爲當你要更改的參數是你不必修改每一個方程。

+1

當然,Farm的構造函數必須在parens裏面,以及它的子模式? – Ingo

+0

@Ingo當然。我還沒有喝過咖啡。謝謝! – kqr

+0

如果我想運行它,我如何將函數輸入到ghci中? – James