Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
899 views
in Technique[技术] by (71.8m points)

haskell - why do these pattern matches overlap?

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 -> deleteRec key q m2
               _ -> (q, m2)

This compiles with the warning

Warning: Pattern match(es) are overlapped
         In a case alternative: _ -> ...

and does not work as I want to. It just seems that for (q4, m4) it always returns

[], fromList []

disregarding what the values of m2 and m are. Is there any local variables where I do not expect them?

What I want to achieve in words: If m2 and m are equal then (q4, m4) should evaluate to deleteRec key q m2, otherwise to (q, m2).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...