Haskell - 模式匹配(es)重叠 [英] Haskell - Pattern match(es) are overlapped

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

问题描述

  test :: String  - >字符串 - > (y:ys)n =错误错误
test'(x:xs)n =错误
$ b test'xyn = n
test'错误
test'(x:xs)(y:ys)n =
if x == y
then test'xs ys n
else test'xs ys(n +1)
test ab = test'ab 0

当我编译这个时,此输出:

 警告:模式匹配重叠

答案总是0,这不是我想要的。如何解决这个问题?

解决方案

test'xyn = n 会匹配每个通话,其他模式不会被考虑。我认为这种情况应该是 test'n = n 。如果您在 end 处移动原始行(当所有其他情况都失败时),您会得到相同的结果,但是您应该写 test'_ _ n = n $ b


$ b这表明您故意忽略某些参数。 $ b

较短的解决方案是:

  test ab |长度a ==长度b =总和$ map fromEnum $ zipWith(/ =)a b 
|否则=错误错误

zipWith 表达式会为每个差异生成 Bool 的列表,其中 True 。函数 fromEnum 映射 False 0 True 1


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?

解决方案

test' x y n = n will match for every call, the other patterns won't be considered. I think this case should be test' "" "" 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 write test' _ _ n = n which shows that you deliberately ignore some of the arguments.

[Edit]

A shorter solution would be:

test a b | length a == length b = sum $ map fromEnum $ zipWith (/=) a b
         | otherwise = error "error" 

The zipWith expression generates a list of Bool which is True for every difference. The function fromEnum maps False to 0 and True to 1.

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

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