0

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])]
                        } 
noogler
  • 167
  • 1
  • 2
  • 16

1 Answers1

5
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 ...
amalloy
  • 89,153
  • 8
  • 140
  • 205
  • Alright this makes sense. I did think case of was like equality. Thank you – noogler Mar 18 '19 at 17:25
  • Would you also be able to advise me on how can I handle break statements in this? I created a new data type for breaks but I am not sure how to handle it – noogler Mar 18 '19 at 17:34
  • 2
    Sounds like you have a number of questions that you might benefit from asking your professor, or whatever source is giving you this exercise. That would be my recommendation. But, if you have another question, and can ask it well as a separate question (not an edit to this one), Stack Overflow is generally available to answer good questions. Whether I personally can help is immaterial. – amalloy Mar 18 '19 at 17:43