借助GHC,我可以启用-Wincomplete-patterns
来捕获可能出现的这两种错误情况。
problem1 :: Either Int String -> Int
problem1 (Left x) = x
problem2 :: Either Int String -> Int
problem2 x = case x of
Left x' -> x'
很明显,我忘记了在这两个函数中都处理Right
情况,GHC会告诉我。但是,在这两种情况下,编译器似乎都没有发出警告就让我失望。
problem3 :: Either Int String -> Int
problem3 x = let Left x' = x in x'
problem4 :: Either Int String -> Int
problem4 = \(Left x) -> x
我仍然忘记处理案件,但是GHC似乎并没有打扰。我是否可以设置编译器标志来捕获类似情况,例如我使用let
或lambda模式匹配但未处理所有情况?理想情况下,如果要执行类似的操作,我会被警告,以便可以将其重构为case
语句等。
当然,出于完整性和后代考虑,与其他编译器相关的答案也受到高度赞赏。
答案 0 :(得分:4)
看来-Wincomplete-uni-patterns
是您所需要的。作为基本上一直使用-Wall
的人,我发现-Wall
或-Wincomplete-patterns
并没有涵盖这些情况,这令人感到惊讶和糟糕。
编辑:似乎已接受将其添加到-Wall
的GHC建议。我不确定状态(我在8.4上选中):https://github.com/ghc-proposals/ghc-proposals/pull/71