有没有用于防护分析的工具?

时间:2015-08-13 19:49:32

标签: haskell logic

我是一名Haskell noob,在阅读Haskell Road中的含义时,我开始关注这个难题。

verdict :: Bool -> Bool -> (Bool, String)
verdict p q | not result  = (False, "LIAR")
            | result && p = (True,  "telling the truth")
            | result      = (True,  "innocent unless proven guilty")
            | otherwise   = (False, "we shouldn't get here")
  where result = (not p) || q
-- map (\x -> verdict (fst x == 1) (snd x == 1)) [(1,1),(1,0),(0,1),(0,0)]

是否有工具可以警告我其他类似的逻辑错误?

2 个答案:

答案 0 :(得分:8)

我想我会以不同的方式编写这个函数:

-- not result
verdict True  False = (False, "LIAR")
-- result && p
verdict True  True  = (True , "telling the truth")
-- result
verdict False _     = (True , "innocent unless proven guilty")
verdict _     True  = (True , "innocent unless proven guilty")
-- otherwise
verdict _     _     = (False, "we shouldn't get here")

那么不仅人类可以忽略哪些条款(最后两个),而且机器也是如此; ghc在默认警告级别上说明了这一点:

test.hs:2:5: Warning:
    Pattern match(es) are overlapped
    In an equation for ‘verdict’:
        verdict _ True = ...
        verdict _ _ = ...

检查警卫重叠一般当然是不可判定的;此外,我不知道会尝试给出一个近似答案的工具。

答案 1 :(得分:4)

这可能更清楚地表达了你的意图:

implies :: Bool -> Bool -> Bool
p `implies` q = not p || q -- The backticks allow infix usage.

-- The assumption is that p `implies` q is a known fact.
verdict :: Bool -> Bool -> (Bool, String)
verdict p q = (result, remark)
    where
    result = p `implies` q
    remark
        | not result = "LIAR"
        | p = "telling the truth"
        | otherwise = "innocent until proven guilty"

Guards是Bool值上模式匹配的语法糖。有关安排模式匹配的一般提示,请参阅Daniel Wagner的回答。