2013-03-26 40 views
2

我剛開始使用Haskell,偶然發現問題。根據Haskell,我有一個模式匹配失敗,但我看不出如何。 這是我嘗試執行代碼:Haskell中的列表中的模式匹配失敗

statistics :: [Int] -> (Int, Int, Int) 
statistics [gradelist] = (amountParticipants, average, amountInsufficient) 
         where 
          amountParticipants= length [gradelist] 
          average= sum[gradelist] `div` amountParticipants 
          amountInsufficient= length [number| number<- [gradelist], number<6] 

我稱之爲與 '統計':

statistics[4,6,4,6] 

這會導致模式匹配失敗,而我希望看到:(4,5,2 )

statistics[6] 

給出了答案:(1,6,0)(這是正確的)。 有人能告訴我爲什麼我的第一個電話會導致這種模式匹配嗎?因爲我敢肯定,我給一個列表作爲參數

+4

'[gradelist]'只匹配一個元素的列表。整個過程只使用'gradelist'。 – 2013-03-26 13:55:42

回答

7

如果你寫statistics [gradelist] = ...你是對含有唯一的元素的列表模式匹配稱gradelist。因此,你的函數只能定義長度爲1的列表(例如[6]);對於空列表([])或包含兩個或更多元素(例如[4,6,4,6])的列表未定義。

你的函數的正確文將

statistics :: [Int]  -> (Int, Int, Int) 
statistics gradelist = (amountParticipants, average, amountInsufficient) 
    where 
    amountParticipants = length gradelist 
    average   = sum gradelist `div` amountParticipants 
    amountInsufficient = length [number| number <- gradelist, number < 6] 

由於@thoferon說,計算的時候,你也將需要爲其中gradelist是空的情況下的特殊安排,以避免被零除average

+0

感謝您的快速反應!現在我終於可以繼續使用這種語言^^ – 2013-03-26 14:39:20

1

模式中的列表語法[ ]解構列表。模式[gradelist]與僅包含一個值的列表匹配,並將其列入列表gradelist中的值。如果嘗試使用包含四個值的列表調用函數,則會出現模式匹配失敗。

要匹配沒有解構它的值,請使用變量作爲模式。

2

正如前面所說的,只需用gradelist替換您的[gradelist]即可。此外,您可能要匹配與[]空列表,以避免被零除average,如:

statistics [] = (0,0,0)