I was trying to define natural number multiplication in Haskell, and kept getting the error below (corresponds to the second natMult definition below).
Prelude> natMult (S (S Z)) (S (S Z))
*** Exception: <interactive>:(4,5)-(5,45): Non-exhaustive patterns in function natPlus
Here's my code:
data Nat = Z | S Nat deriving (Show)
natPlus :: Nat -> Nat -> Nat
natPlus Z a = a
natPlus (S a) (S b) = natPlus a (S (S b))
After a bit of tinkering, I realized this definition works fine, whereas the second one below is broken. The only difference is the order of the input parameters for natPlus.
-- works fine
natMult :: Nat -> Nat -> Nat
natMult Z a = Z
natMult (S a) b = natPlus (natMult a b) b
-- gives gives the error above
natMult :: Nat -> Nat -> Nat
natMult Z a = Z
natMult (S a) b = natPlus b (natMult a b)
Can anyone explain why this error arises?
---Edit--- The below definition is complete and solves the problem. Thanks for the suggestions
natPlus Z a = a
natPlus (S a) b = natPlus a (S b)