codeX
codeX

Reputation: 5428

Haskell Warning: Pattern match is redundant

I have created a function in Haskell to counts the number of functions and operators in the given expression.

size :: Expr -> Int
size (Num n) = 1
size x       = 1
size (Function f e) = 1 + size e
size (Operation o e1 e2) = 1 + size e1 + size e2

Though it's working as expected without any errors, I am getting a warning: [-Woverlapping-patterns] saying Pattern match is redundant. Any suggestions will be appreciated!

Upvotes: 1

Views: 1075

Answers (1)

radrow
radrow

Reputation: 7159

The order of case clause matters – the incoming value is matched to patterns from top to bottom and if any of these checks succeeds, that option is taken. In your case a variable x will successfully match to anything by assigning x to that thing. Therefore, all cases below it won't ever be considered.

Perhaps you wanted:

size :: Expr -> Int
size (Num n) = 1  -- btw, you can skip this line
size (Function f e) = 1 + size e
size (Operation o e1 e2) = 1 + size e1 + size e2
size x       = 1

Upvotes: 3

Related Questions