1
votes

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!

1
Everything after the x will never "fire", since x will capture any value. - Willem Van Onsem
"Though it's working as expected". Are you sure about that? Try to find a value for e such that size e returns anything except 1. - chepner

1 Answers

3
votes

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