我想用CNF的命题公式解析字符串到DIMACS,从而在haskell中嵌套一个int列表。该格式适用于haskell picosat绑定,它似乎比其他SAT解决方案性能更高。
问题是,我的代码实现这是太复杂了,现在我正在寻找一个可能的bug,是不明显的发现。
(我的方法是使用haskell hat包,更改包,使其使用字符串而不是单个字符作为变量名,用hat解析表达式,然后将结果表达式转换为DIMACS格式。)
我想解析一个用CNF表示法表示命题公式的字符串(参见下面的示例)。结果应该是一个嵌套的int型列表。因此,结果应该适合作为haskell picosat绑定一部分的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)
您可能不需要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)
我维护您提到的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
见:http://hackage.haskell.org/package/picologic