Haskell中的逻辑公式打印

时间:2014-01-23 16:55:18

标签: haskell functional-programming

我正在处理一些奇怪的问题。我想编写一个Haskell程序,它将打印给定的逻辑公式,即

print (showFormula (I (N (Z 'p')) (A (C (Z 'p') (Z 'q')) (Z 'r'))))

(我暗示,A - 替代,N - 否定,C - 连词和Z - 字符)

应该打印出类似的内容:

"(~p => ((p & q) | r))"

到目前为止,我的代码看起来像这样:

data Formula
    = Z Char
    | V Bool
    | N Formula
    | C Formula Formula
    | A Formula Formula
    | I Formula Formula
    | Join Formula Formula

showFormula :: Formula -> String
showFormula (Z c) = [c]
showFormula (Join a b) = (showFormula a) ++ (showFormula b)

showFormula (N a) = '~':(showFormula a)
showFormula (C a b) = "("++(showFormula a)++" & "++(showFormula b)++")"
showFormula (A a b) = "("++(showFormula a)++" | "++(showFormula b)++")"
showFormula (I a b) = "("++(showFormula a)++" => "++(showFormula b)++")"

它确实打印了正确的字符串,但只有当您输入像(C (Z 'a') (Z 'b'))这样的简单公式时才会打印,并且它会与某些扩展公式崩溃。我知道问题是将一个Formula参数而不是String传递给showFormula函数,但我不知道如何更改它。请给我一些建议如何解决这个问题。

2 个答案:

答案 0 :(得分:4)

如果使用-Wall标记编译代码,它将显示以下警告:

fml.hs:4:1: Warning:
    Pattern match(es) are non-exhaustive
    In an equation for `showFormula': Patterns not matched: V _

您忘记为V编写showFormula案例,因此如果达到该值,它将崩溃,类似于head函数如果使用空列表调用它时崩溃的方式。< / p>

答案 1 :(得分:2)

您似乎错过了模式匹配中的(V b)案例。

data Formula
    = Z Char
    | V Bool
    | N Formula
    | C Formula Formula
    | A Formula Formula
    | I Formula Formula
    | Join Formula Formula

showFormula :: Formula -> String
showFormula (V b) = show b
showFormula (Z c) = [c]
showFormula (Join a b) = (showFormula a) ++ (showFormula b)

showFormula (N a) = '~':(showFormula a)
showFormula (C a b) = "("++(showFormula a)++" & "++(showFormula b)++")"
showFormula (A a b) = "("++(showFormula a)++" | "++(showFormula b)++")"
showFormula (I a b) = "("++(showFormula a)++" => "++(showFormula b)++")"

main :: IO ()
main = do
  print (showFormula (I (N (Z 'p')) (A (C (Z 'p') (Z 'q')) (Z 'r'))))
  -- "(~p => ((p & q) | r))"