【问题标题】:Non-exhaustive patterns error with empty list [duplicate]空列表的非详尽模式错误[重复]
【发布时间】:2012-03-08 02:51:33
【问题描述】:

我声明了一个新的内存类型,然后使用一个函数来更新它。当我向列表中添加值时,程序编译并正常工作,但如果我的列表为空,我会收到错误:

*** Exception: Non-exhaustive patterns in function 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)]
    | otherwise   = h : update n x t

【问题讨论】:

    标签: haskell


    【解决方案1】:

    这是因为您的代码没有涵盖空列表案例。 特别是: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
    

    【讨论】:

    • 还需要添加到第二次检查 n== fst h
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多