[英]Extending propositional logic to modal logic in Haskell
我在Haskell中編寫了一些用於建模命題邏輯的代碼
data Formula = Prop {propName :: String}
| Neg Formula
| Conj Formula Formula
| Disj Formula Formula
| Impl Formula Formula
| BiImpl Formula Formula
deriving (Eq,Ord)
但是,由於數據類型已關閉,因此沒有自然的方法將其擴展到Modal Logic。 因此,我認為我應該使用類來代替。 這樣,我可以在以后輕松地在不同的模塊中添加新的語言功能。 問題是我不知道如何寫它。 我想要像下面這樣的東西
type PropValue = (String,Bool) -- for example ("p",True) states that proposition p is true
type Valuation = [PropValue]
class Formula a where
evaluate :: a -> Valuation -> Bool
data Proposition = Prop String
instance Formula Proposition where
evaluate (Prop s) val = (s,True) `elem` val
data Conjunction = Conj Formula Formula -- illegal syntax
instance Formula Conjunction where
evaluate (Conj φ ψ) v = evaluate φ v && evaluate ψ v
錯誤當然是在Conjunction的定義中。 但是,我不清楚如何重寫它以使其有效。
這應該工作:
data Conjunction f = Conj f f
instance Formula f => Formula (Conjunction f) where
evaluate (Conj φ ψ) v = evaluate φ v && evaluate ψ v
但是,我不確定類型類是否是您正在嘗試實現的正確工具。
也許你可以嘗試使用顯式類型級函子並重復它們:
-- functor for plain formulae
data FormulaF f = Prop {propName :: String}
| Neg f
| Conj f f
| Disj f f
| Impl f f
| BiImpl f f
-- plain formula
newtype Formula = F {unF :: FormulaF Formula}
-- functor adding a modality
data ModalF f = Plain f
| MyModality f
-- modal formula
newtype Modal = M {unM :: ModalF Modal}
是的,這不是非常方便,因為F,M,Plain
等構造函數有時會受到影響。 但是,與類型類不同,您可以在此處使用模式匹配。
作為另一種選擇,使用GADT:
data Plain
data Mod
data Formula t where
Prop {propName :: String} :: Formula t
Neg :: Formula t -> Formula t
Conj :: Formula t -> Formula t -> Formula t
Disj :: Formula t -> Formula t -> Formula t
Impl :: Formula t -> Formula t -> Formula t
BiImpl :: Formula t -> Formula t -> Formula t
MyModality :: Formula Mod -> Formula Mod
type PlainFormula = Formula Plain
type ModalFormula = Formula Mod
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.