【问题标题】:Haskell: Non-exhaustive patterns in functionHaskell:函数中的非穷举模式
【发布时间】:2016-08-04 06:59:43
【问题描述】:

我得到以下代码的非详尽模式异常

--determine which list is longer
longer::[a]->[a]->Bool
longer [] [] = False
longer _ [] = True
longer (_:[]) (_:[]) = False
longer (_:xs) (_:ys) = longer xs ys

我不明白我在这里做错了什么。

【问题讨论】:

  • 使用:ghc -Wall prog.hs 和 ghc 应该会告诉您未考虑的模式。

标签: haskell pattern-matching


【解决方案1】:

你没有处理这个案子:

longer [] _ = undefined

模式(_:[]) 假设您在列表中至少有一个元素。在您的代码中,您错过了第一个列表为空而第二个列表可能不为空的情况。

【讨论】:

  • 或者它应该是longer [] _ = False
  • 我将把它留给 OP。 :)
【解决方案2】:

您需要 4 个案例,但您不需要将两个单例列表视为单独的案例。

longer :: [a] -> [a] -> Bool

-- 1) Two empty lists
longer [] [] = False
-- 2) An non-empty list and an empty list
longer _ []  = True
-- 3) An empty list and a non-empty list
longer [] _ = ???
-- 4) Two non-empty lists
longer (_:xs) (_:ys) = longer xs ys

实际上,您只需要按正确顺序排列 3 个案例,具体取决于 longer [] _ 应该是什么。

-- First case: if longer [] _ is suppose to be True
longer :: [a] -> [a] -> Bool
longer [] [] = True
longer (_:xs) (_:ys) = longer xs ys
-- We get this far if one is empty and the other is not,
-- but we don't care which one is which.
longer _ _ = False

-- Second case: if longer [] _ is supposed to be False
longer :: [a] -> [a] -> Bool
longer (_:xs) (_:ys) = longer xs ys
longer _ [] = True
longer [] _ = False -- This covers longer [] [] as well.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多