Haskell - 模式匹配重叠
test :: String -> String -> Int
test' x y n = n
test' "" (y:ys) n = error "error"
test' (x:xs) "" n = error "error"
test' (x:xs) (y:ys) n =
if x == y
then test' xs ys n
else test' xs ys (n+1)
test a b = test' a b 0
当我编译这个时,我得到这个输出:
Warning: Pattern match(es) are overlapped
答案总是“0”,这不是我想要的。代码有什么问题以及如何修复它?
test :: String -> String -> Int
test' x y n = n
test' "" (y:ys) n = error "error"
test' (x:xs) "" n = error "error"
test' (x:xs) (y:ys) n =
if x == y
then test' xs ys n
else test' xs ys (n+1)
test a b = test' a b 0
When I compile this, I get this output:
Warning: Pattern match(es) are overlapped
And the answer is always "0", which is not what I intended. What is the problem with the code and how to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
test' xyn = n
将匹配每次调用,其他模式将不被考虑。我认为这种情况应该是test' "" "" n = n
。如果将原始行移到末尾(当所有其他情况都失败时),您会得到相同的结果,但是您应该编写test' _ _ n = n
,其中显示你故意忽略一些论点。[编辑]
一个较短的解决方案是:
zipWith
表达式生成一个Bool
列表,对于每个不同之处。函数fromEnum
将False
映射到0
,将True
映射到1
。test' x y n = n
will match for every call, the other patterns won't be considered. I think this case should betest' "" "" n = n
. You get the same result if you move your original line at the end (when all other cases fail), but then you should writetest' _ _ n = n
which shows that you deliberately ignore some of the arguments.[Edit]
A shorter solution would be:
The
zipWith
expression generates a list ofBool
which isTrue
for every difference. The functionfromEnum
mapsFalse
to0
andTrue
to1
.按顺序尝试这些模式。
test'
的第一个模式始终匹配,因此始终使用该大小写。第一种情况可能应该是相反。
The patterns are tried in order. The first of your patterns for
test'
always matches, so that case is always used. The first case should probably beinstead.