首页 文章

Haskell:功能上的非详尽模式

提问于
浏览 289
0

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

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

我不明白我在做错了什么 .

2 回答

  • 4

    您需要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
    

    实际上,根据 longer [] _ 应该是什么,你只需要正确的3个案例 .

    -- 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.
    
  • 2

    你没有处理这个案子:

    longer [] _ = undefined
    

    模式 (_:[]) 假定列表中至少有一个元素 . 在您的代码中,当第一个列表为空且第二个列表可能不为空时,您将错过这种情况 .

相关问题