2012-03-08 47 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