Alex
Alex

Reputation: 325

Non-exhaustive patterns in my function

The following function compiles but when run outputs a non-exhaustive pattern error

hufMerge :: CodeTable -> CodeTable -> CodeTable
hufMerge [(x,a)] [(y,b)] = foldr (:) (map add0 [(x,a)]) (map add1 [(y,b)])
hufMerge [(x,a)] [] = map add0 [(x,a)]
hufMerge [] [(y,b)] = map add1 [(y,b)]
hufMerge [] [] = []

where

type CodeTable = [(Char,[Integer])]

I am not seeing where the error is coming from, do I have to do 2^4 cases, where out of [(x,a)] [(y,b)], x, a, y, or b can be zero?

Upvotes: 1

Views: 254

Answers (1)

daniel gratzer
daniel gratzer

Reputation: 53871

I believe you meant

hufMerge :: CodeTable -> CodeTable -> CodeTable
hufMerge [] [] = []
hufMerge xs [] = map add0 xs
hufMerge [] ys = map add1 ys
hufMerge xs ys = foldr (:) (map add0 xs) (map add1 ys)

If you match on [foo] you're matching on a list of exactly length one and then matching on that one element with whatever pattern foo is.

As a quick catalog on how to match on lists,

  1. Ignore them completely, as always _ ignores the value
  2. Match with any variable, The pattern xs for example will bind with any list
  3. Match head-tail, (x:xs) will bind the first element to x and rest to xs
  4. Match element-wise [x, y, z ...] which is just sugar for x : y : z .... : []

Upvotes: 7

Related Questions