Haskell - 模式匹配重叠

发布于 2024-12-08 05:28:29 字数 416 浏览 0 评论 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

当我编译这个时,我得到这个输出:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空城之時有危險 2024-12-15 05:28:29

test' xyn = n 将匹配每次调用,其他模式将不被考虑。我认为这种情况应该是test' "" "" n = n。如果将原始行移到末尾(当所有其他情况都失败时),您会得到相同的结果,但是您应该编写 test' _ _ n = n ,其中显示你故意忽略一些论点。

[编辑]

一个较短的解决方案是:

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

zipWith 表达式生成一个 Bool 列表,对于每个不同之处。函数 fromEnumFalse 映射到 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 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.

月光色 2024-12-15 05:28:29

按顺序尝试这些模式。 test' 的第一个模式始终匹配,因此始终使用该大小写。第一种情况可能应该是

test' "" "" n = n

相反。

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 be

test' "" "" n = n

instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文