空列表中的非详尽模式错误

apo*_*tsi 0 haskell

我正在声明一种新的内存类型,然后使用一个函数来更新它.当我向列表中添加值时,程序编译并正常工作,但如果我的列表为空,则会出现错误"函数中的非详尽模式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 
Run Code Online (Sandbox Code Playgroud)

Grz*_*ała 5

这是因为您的代码不包含空列表大小写.特别是:h:t == []永远不会评估True.h: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
Run Code Online (Sandbox Code Playgroud)