Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 具有空列表的非穷举模式错误_Haskell - Fatal编程技术网

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