Non-exhaustive patterns error with empty list

前端 未结 1 852
逝去的感伤
逝去的感伤 2021-01-26 06:53

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 e

相关标签:
1条回答
  • 2021-01-26 07:19

    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
    
    0 讨论(0)
提交回复
热议问题