【发布时间】:2015-11-01 21:10:16
【问题描述】:
我试图在 Haskell 中创建一个命题逻辑模型,我需要一个函数来将一些逻辑规则应用于特定的子表达式。函数“apply”获取一个列表,该列表指示子表达式在树中的位置(根据左右序列)、一个逻辑规则和一个逻辑表达式,并返回一个新的逻辑表达式。
data LogicExp a = P a |
True' |
False' |
Not' (LogicExp a) |
(LogicExp a) :& (LogicExp a) |
(LogicExp a) :| (LogicExp a) |
(LogicExp a) :=> (LogicExp a) |
(LogicExp a) := (LogicExp a)
deriving Show
type LExp = LogicExp String
data Position = L | R
deMorgan :: LExp -> LExp
deMorgan (e1 :& e2) = Not' ((Not e1) :| (Not e2))
deMorgan (e1 :| e2) = Not' ((Not e1) :& (Not e2))
deMorgan x = x
apply :: [Position] -> (LExp -> LExp) -> LExp -> LExp
apply [] f e = f e
apply (L:xs) f (e1 :& e2) = (apply xs f e1) :& e2
apply (R:xs) f (e1 :& e2) = e1 :& (apply xs f e2)
apply (L:xs) f (e1 :| e2) = (apply xs f e1) :| e2
apply (R:xs) f (e1 :| e2) = e1 :| (apply xs f e2)
apply (L:xs) f (e1 :=> e2) = (apply xs f e1) :=> e2
apply (R:xs) f (e1 :=> e2) = e1 :=> (apply xs f e2)
apply (L:xs) f (e1 := e2) = (apply xs f e1) := e2
apply (R:xs) f (e1 := e2) = e1 := (apply xs f e2)
apply (x:xs) f (Not' e) = apply xs f e
该功能运行良好。但是我可以使用一些数据构造函数“通配符”来拥有像这样更简单的功能吗?
apply :: [Position] -> (LExp -> LExp) -> LExp -> LExp
apply [] f e = f e
apply (L:xs) f (e1 ?? e2) = (apply xs f e1) ?? e2
apply (R:xs) f (e1 ?? e2) = e1 ?? (apply xs f e2)
apply (x:xs) f (Not' e) = apply xs f e
【问题讨论】:
标签: haskell pattern-matching logic