user1308560
user1308560

Reputation: 409

Why does this code produce a "non-exhaustive patterns in case" error?

I was trying out the following example given in this tutorial.

What I could not understand is how the case guards for the cases 'c' and _ don't use the on at all?

I modified the code as given here, but then when I run it I got the error "Non-exhaustive patterns in case":

*StateGame> main "accaaaa"
*** Exception: state1.hs:(27,5)-(31,36): Non-exhaustive patterns in case

Why is this so?

Upvotes: 1

Views: 414

Answers (1)

hammar
hammar

Reputation: 139870

A case guard is a boolean expression which is checked after successfully matching the corresponding pattern. If it evaluates to True, that branch is chosen. Otherwise, Haskell will keep trying each case from top to bottom.

In your example, all the cases have the guard expression on:

case x of
   'a' | on -> ...
   'b' | on -> ...
   'c' | on -> ...
   _   | on -> ...

Thus, when on is False, none of the branches can be chosen, so you get a "Non-exhaustive patterns in case" exception.

Upvotes: 6

Related Questions