空列表的非穷举模式错误 [英] Non-exhaustive patterns error with empty list
问题描述
我正在声明一种新的内存类型,然后使用一个函数对其进行更新.当我向列表中添加值时,该程序可以编译并运行良好,但是如果列表为空,则会出现错误函数update
中的非穷举模式".这是我的代码,如果可以的话请帮助我:
I am declaring a new type for memory and then use a function to update it. The program compiles and works fine when I add values to the list, but if my list is empty I get the error "non-exhaustive patterns in function update
". Here is my code, if you can please help me:
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
绑定到列表的其余部分.
This is because your code doesn't cover the empty list case.
In particular this: h:t == []
will never evaluate to True
. h:t
is a pattern which will only match a non-empty list: it binds h
to the head of the list and t
to the rest of the list.
因此您的函数需要处理三种情况:
So your function needs to handle three cases:
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
这篇关于空列表的非穷举模式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!