1

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:

*** Exception: 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)]
    | otherwise   = h : update n x t
0

1 Answer 1

6

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
1
  • also it needs to add to the second check n== fst h
    – apoellitsi
    Mar 8, 2012 at 3:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.