【问题标题】:Haskell - Pattern match(es) are overlappedHaskell - 模式匹配重叠
【发布时间】:2011-11-30 17:28:14
【问题描述】:
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”,这不是我想要的。代码有什么问题以及如何解决?

【问题讨论】:

    标签: haskell pattern-matching


    【解决方案1】:

    test' x y n = n 将匹配每个调用,不会考虑其他模式。我觉得这个case应该是test' "" "" n = n。如果您将原始行移到 end(当所有其他情况都失败时),您会得到相同的结果,但是您应该写 test' _ _ n = n 这表明您故意忽略了一些参数。

    [编辑]

    更短的解决方案是:

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

    zipWith 表达式生成Bool 的列表,每个差异都是True。函数fromEnumFalse 映射到0True1

    【讨论】:

      【解决方案2】:

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

      test' "" "" n = n
      

      改为。

      【讨论】:

        猜你喜欢
        • 2012-02-18
        • 1970-01-01
        • 2017-11-13
        • 2021-05-22
        • 2017-05-08
        • 2019-03-01
        • 2016-10-29
        • 2017-10-12
        • 2019-05-17
        相关资源
        最近更新 更多