2012-03-08 46 views
0

我聲明瞭一種新的內存類型,然後使用函數來更新它。該程序編譯和工作正常,當我將值添加到列表中,但如果我的列表爲空,我會收到錯誤「函數update中的非窮舉模式」。這裏是我的代碼,如果你可以請幫助我:非詳盡模式與空列表錯誤

type Name = [Char] 
type Memory = [(Name,Integer)] 

update :: Name ->Integer -> Memory -> Memory 
update n x (h:t) 
    |(fst h==n) =(n,x):t 
    |((h:t) == []) = (n,x):[] 
    |(fst t==x) = h:(n,t) 
    |(t==[]) = h:(n,x):[] 
    |otherwise = h:update n x t 

回答

5

這是因爲你的代碼不包括空列表大小寫。 特別是:h:t == []永遠不會評估爲Trueh:t是僅與非空列表匹配的模式:它將h綁定到列表的頭部,將t綁定到列表的其餘部分。

所以你的函數需要處理三種情況:

update n x [] = (n,x):[]      -- empty list 
update n x (h:t) | n == fst h = (n,x):t   -- key equal to n 
       | otherwise = h:update n x t -- key not equal to n 
+0

還需要添加到第二檢查n ==可FST^h – apoellitsi 2012-03-08 03:56:18