为什么这些模式匹配重叠? [英] why do these pattern matches overlap?

查看:135
本文介绍了为什么这些模式匹配重叠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 (q,m)< -  newRq $ b $为什么我的模式匹配do块重叠? b让m2 = appendMsgfirstkey m 
(q4,m4)= case $ m2
m - > deleteRec键q m2
_ - > (q,m2)

这个警告符合

 警告:模式匹配重叠
在另一种情况下:_ - > ...

并且不能按我的想法工作。它似乎是(q4,m4)它始终返回

  [],fromList [] 

无视m2和m的值。是否有任何我不指望他们的局部变量?



我想用文字来实现:如果m2和m相等,那么(q4,m4)应该评估为 deleteRec key q m2 ,否则为(q,m2)。 > m )匹配所有内容并将其分配给 m 。第二个匹配所有内容并丢弃它( _ ),但没有任何匹配,因为 m 将获得所有内容。



我认为你的意思是为了像 switch 语句一样工作,但它实际上可以作为一组模式,很像函数声明。因此,您的案例与以下类似:

  check m2 
其中check m = deleteRec key q m2
check _ =(q,m2)

在这段代码中,如果最好使用

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

您如果语句不同,也可以考虑缩进

  if m == m2 
然后deleteRec key q m2
else(q,m2)

应该也可以。



然而,一般来说,你可以在 case 语句中使用警卫,所以这可以起作用太:

  case m2 of 
val | m2 == m - > deleteRec键q m2
|否则 - > (q,m2)

如果,但是如果你有更多的分支或者需要做一些实际的模式匹配,这是有道理的。


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).

解决方案

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.

这篇关于为什么这些模式匹配重叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆