why do these pattern matches overlap?

前端 未结 1 1600
[愿得一人]
[愿得一人] 2020-12-06 23:57

Why do my pattern matches inside a do block overlap?

 (q, m) <- newRq
 let m2 = appendMsg \"first\" key m
     (q4, m4) = case m2 of   
               m -         


        
相关标签:
1条回答
  • 2020-12-07 00:59

    The first pattern in the case (m) matches everything and assigns it to m. The second one matches everything and discards it (_), but has nothing left to match because m will get everything.

    I think you meant for the case to work like a switch statement, but it actually works as a set of patterns, much like a function declaration. So your case is the same as something like:

    check m2
      where check m = deleteRec key q m2
            check _ = (q, m2)
    

    In this code, you're probably best off just using an if:

    if m == m2 then deleteRec key q m2 else (q, m2)
    

    You might also consider indenting the if statement differently:

    if   m == m2
    then deleteRec key q m2
    else (q, m2)
    

    should also work.

    However, in general, you can actually use guards in a case statement, so this would work too:

    case m2 of
      val | m2 == m   -> deleteRec key q m2
          | otherwise -> (q, m2)
    

    This is obviously harder to read than an if, but if you had more branches or needed to do some actual pattern matching, it would make sense.

    0 讨论(0)
提交回复
热议问题