我想用CNF中的命题公式将字符串解析为DIMACS,因此在haskell中嵌套了一个int列表。该格式适用于haskell picosat绑定,这些绑定似乎比SAT解决的其他选项更具性能。
问题在于我实现此代码的代码太复杂了,现在我正在寻找一个可能无法找到的错误。
(我的方法是使用haskell hatt包,更改包,因此它使用字符串而不是单个字符用于变量名称,用hatt解析表达式,然后将结果表达式转换为DIMACS格式。)
我想解析一个表示CNF表示法中的命题公式的字符串(参见下面的示例)。结果应该是一个嵌套的int列表。因此,结果应该适合作为haskell picosat bindings的一部分的solveAll
。
输入:
-- "&" ... conjunction
-- "|" ... disjunction
-- "-" ... not operator
let myCNF = "GP & (-GP | Ma) & (-Ma | GP) & (-Ma | TestP) & (-Ma | Alg) & (-Ma | Src) & (-Ma | Hi) & (-Ma | Wg | X | Y) & -Z"
结果:
-- DIMACS format
-- every Variable (e.g., "GP") gets a number, say GP gets the int num 1
-- in case of not GP (i.e., "-GP") the int number representing the variable is negative, thus -1
-- Note: I hope I didn't do a type
let myresult = [[1], [-1, 2], [-2, 1], [-2, 3], [-2, 3], [-2, 5], [-2, 6], [-2, 7, 8, 9], [-10]]
let myvars = ["GP", "Ma", "TestP", "Alg", "Src", "Hi", "Wg", "X", "Y", "Z"]
-- or alternativly the variables are stored in an associative array
let varOtherWay = (1, GP), (2, Ma) (3, TestP), (4, Alg), (5, Src), (6, Hi), (7, Wg), (8, X), (9, Y), (10, Z)
答案 0 :(得分:2)
您可能不需要parsec来读取CNF中的语句,您可以使用map (splitOn "|") . splitOn "&"
提取变量 - 其余的只是将变量分配给变量:
import qualified Data.Map as M
import Data.List.Split
import Control.Monad.State
deleteMany c [] = []
deleteMany c (x:xs)
| x`elem`c = deleteMany c xs
| otherwise = x : deleteMany c xs
parseStatement :: String -> ( [[Int]] , M.Map Int String )
parseStatement =
f . flip runState (M.empty, 1) . mapM (mapM (readVar . toVar)) . varsOf . deleteMany "() "
where
f (r, (m, _)) = (r , M.fromList $ map (uncurry (flip (,))) $ M.toList m)
varsOf = map (splitOn "|") . splitOn "&"
toVar ('-':v) = (True , v)
toVar v = (False, v)
readVar (b,v) = do
(m, c) <- get
case M.lookup v m of
Nothing -> put (M.insert v c m, c+1) >> return (neg b c)
Just n -> return (neg b n)
neg True = negate
neg False = id
也许parsec版本对于错误处理或者集成到更大的解析器中仍然很有用:
parseStatement = parse statement "" . deleteMany " "
statement = sepBy1 clause (char '&')
clause = between (char '(') (char ')') x <|> x
where x = sepBy1 var (char '|')
var = do
n <- maybe False (const True) <$> optionMaybe (char '-')
v <- many1 (noneOf "&|-() ")
return (n, v)
答案 1 :(得分:0)
我维护你提到的picosat绑定。在看到这个问题之后,我在Hackage中添加了一个新的picologic
包,它构建在picosat
之上,用命题公式解析和转换并将它们提供给SAT求解器。
import Picologic
p, q, r :: Expr
p = readExpr "~(A | B)"
q = readExpr "(A | ~B | C) & (B | D | E) & (D | F)"
r = readExpr "(φ <-> ψ)"
ps = ppExprU p
-- ¬(A ∨ B)
qs = ppExprU q
-- ((((A ∨ ¬B) ∨ C) ∧ ((B ∨ D) ∨ E)) ∧ (D ∨ F))
rs = ppExprU (cnf r)
-- ((φ ∧ (φ ∨ ¬ψ)) ∧ ((ψ ∨ ¬φ) ∧ ψ))
main :: IO ()
main = solveProp p >>= putStrLn . ppSolutions
-- ¬A ¬B
-- ¬A B
-- A ¬B