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
Noughtmare
  • 9,410
  • 1
  • 12
  • 38
apoellitsi
  • 249
  • 6
  • 21

1 Answers1

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
Grzegorz Chrupała
  • 3,053
  • 17
  • 24