Reputation: 45
I have this piece of code
middleNumber:: Int -> Int -> Int -> Int
middleNumber a b c
| a == b && a == c = a
| a == b || a == c = a
| b == c = b
| b < a && a < c || c < a && a < b = a
| a < b && b < c || c < b && b < a = b
| otherwise = c
I want to use pattern matching to catch all other input pattern, I tried to use
middleNumber _ = error "Wrong input"
and
middleNumber _ _ _ = error "Wrong input"
But they seem do not work. Appreciate any helps!
Upvotes: 0
Views: 562
Reputation: 56
It's not clear which input is "wrong".
However, the otherwise-guard always evaluates to True
and thus it will catch all orhter cases.
If you really have cases that are wrong input, then you should replace the otherwise
-guard by the right condition. Finally,
you can add as a last line, which will only be used if no guard evaluates to True
.
middleNumber _ _ _ = error "Wrong input"
that is
middleNumber :: Int -> Int -> Int -> Int
middleNumber a b c
| a == b && a == c = a
| a == b || a == c = a
| b == c = b
| b < a && a < c || c < a && a < b = a
| a < b && b < c || c < b && b < a = b
| ...conditions for c being the middle number... = c
middleNumber _ _ _ = error "Wrong input"
If no guard evaluates to True
the last line catches all other cases.
Upvotes: 4
Reputation: 370445
The patterns a b c
already match any possible arguments that your function may receive, so any patterns you add in addition to that would just be unreachable code. There simply are no other input patterns for you to catch.
Upvotes: 5