mehdix_
mehdix_

Reputation: 479

Non-exhaustive pattern matching

I am working on a project that works on Modular Arithmetic. I ran into the pattern matching problem when I'm invoking the function. Here is the constructor of type Modular. madd takes two instance of type Modular, and is suppose to add them up returning of type Modular.

data Modular = Mod Integer Integer deriving Show
instance (Eq Modular) where
  (Mod a1 m1) == (Mod a2 m2) = m1==m2 && mod (a1-a2) m1 == 0


-- Adds two modular numbers of the same modulus
madd :: Modular -> Modular -> Modular
madd (Mod a1 m1) (Mod a2 m2) | m1 == m2 = Mod (mod (a1+a2) m1) m1

Can anyone help me why am I getting non-exhaustive pattern matching? the error is like this:

Warning: Pattern match(es) are non-exhaustive
         In an equation for `madd':
             Patterns not matched: (Mod _ _) (Mod _ _)

BTW, I am using haskell plugin within eclipse IDE.

Upvotes: 1

Views: 993

Answers (3)

Daniel Araujo
Daniel Araujo

Reputation: 21

"Pattern match(es) are non-exhaustive"

madd :: Modular -> Modular -> Modular
madd (Mod a1 m1) (Mod a2 m2) | m1 == m2 = Mod (mod (a1+a2) m1) m1
                           **| otherwise = ...** you have to write the answer to this case

Upvotes: 0

jamshidh
jamshidh

Reputation: 12070

For a quick fix, you can always add your own error reporting:

madd (Mod a1 m1) (Mod a2 m2) | m1 == m2 = Mod (mod (a1+a2) m1) m1
madd (Mod a1 m1) (Mod a2 m2) = 
                  error ("You can not add  a mod " ++ show m1 
                             ++ " number with a " show m2 ++ " number.")

Not only does this get rid of the warning, but it also can be used to give you more information if the case is called. Of course if it is triggered, the program will crash (as it would without the extra case).... If I want to communicate an error to the end user I would put something less harsh in.

Upvotes: 2

stonemetal
stonemetal

Reputation: 6208

That is a warning not an error. The compiler isn't smart enough to check guard statements to make sure they cover all possible matches so it excludes pattern matches with guards from the exhaustive pattern check. If you don't have patterns that match all possible inputs without a guard you will have to live with it, or disable it.

Upvotes: 1

Related Questions