Haskell中奇怪的模式匹配失败

时间:2016-03-07 13:18:23

标签: haskell pattern-matching

我写了以下函数:

addToDT :: (Ord a) => DocumentTable a -> [a] -> DocumentTable a
addtoDT t [] = t
addToDT t (x:xs) =
   addToDT DocumentTable { tableLength = tableLength t + maybe 0 (const 1) (M.lookup x (table t))
                         , table = M.insertWith (+) x 1 (table t)
                         } xs

DocumentTable是存储其长度的地图:

data DocumentTable a = DocumentTable { table :: Map a Int
                                     , tableLength :: Int
                                     }  

addToDT制作一张地图,其中包含列表中每个不同a的出现次数。

当我使用它时,我得到Non-exhaustive patterns in function addToDTtraceShow向我展示了使用空列表调用addToDT时发生的情况。如果我将addToDT替换为:

addToDT :: (Ord a) => DocumentTable a -> [a] -> DocumentTable a
addToDT t xxx
  | null xxx = t
  | otherwise = addToDT DocumentTable { tableLength = tableLength t + maybe 0 (const 1)(M.lookup x (table t))
                                      , table = M.insertWith (+) x 1 (table t)
                                      } xs
  where (x:xs) = xxx

然后它有用......但我真的不明白为什么。有人可以向我解释为什么模式匹配失败了吗?

1 个答案:

答案 0 :(得分:1)

简单地

addtoDT t [] = t    -- this is another function since `to` isn't `To`

:)