Search code examples
haskellcase-expression

case of redundant pattern matching


I am trying to write a haskell interpeter for different kind of statements. One such is a switch statement. I have done the following as of now but I am stuck and I keep getting redundant pattern matching warning for the ( _ -> if length ) line in the case expression. It is passing the test if the first case expression is the right one but if not the test is failing. Any help appreciated, thanks

 interpret :: Program -> Memory -> Either Err Memory
 interpret [] memory = Right memory
 interpret (SwitchStmt var c:p) memory = let case1 = fst(c!!0)
                                            case2 = snd(c!!0)
                                         in do
                                           val <- evaluate var memory
                                           case val of case1 -> (interpret (case2++p) memory)
                                                        _ -> if length c > 1 then interpret ((SwitchStmt var (tail c)):p) memory
                                                             else interpret p memory 

I have defined data types as such :

data Stmt = SwitchStmt{
                        switchVar  :: Expr,
                        switchCase :: [(Expr,[Stmt])]
                        } 

Solution

  • case val of case1
    

    does not do what you think it does, namely, check whether val is equal to case1. It introduces a new binding named case1, shadowing the existing binding, whose value is val. You don't get equality comparisons for free: you have to ask for them, by using ==, perhaps in a guard clause, or in an if expression. So, you do have two redundant patterns: the _ clause will never be entered, because the case1 pattern matches all possible inputs.

    Instead, write an equality test yourself. There are nicer ways to do it, but a way to do that while making minimal changes to your existing function might be:

    ... do
      val <- evaluate var memory
      if val == case1
        then interpret ...
        else interpret ...