Haskell 具有空列表的非穷举模式错误
我正在为内存声明一个新类型,然后使用一个函数来更新它。当我向列表中添加值时,程序可以编译并正常工作,但如果列表为空,则会出现错误“函数中的非穷举模式Haskell 具有空列表的非穷举模式错误,haskell,Haskell,我正在为内存声明一个新类型,然后使用一个函数来更新它。当我向列表中添加值时,程序可以编译并正常工作,但如果列表为空,则会出现错误“函数中的非穷举模式更新”。这是我的代码,如果您能帮助我: type Name = [Char] type Memory = [(Name,Integer)] update :: Name ->Integer -> Memory -> Memory update n x (h:t) |(fst h==n) =(n,x):t |((
更新
”。这是我的代码,如果您能帮助我:
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
这是因为您的代码没有覆盖空列表的情况。 特别是:
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
这是因为您的代码没有覆盖空列表的情况。 特别是:
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
它还需要添加到第二个检查n==fst halso,因此它需要添加到第二个检查n==fst h