Created
April 28, 2011 01:04
-
-
Save tautologico/945597 to your computer and use it in GitHub Desktop.
Calculating truth tables for propositional formulas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List ( nub ) | |
import Data.Maybe ( fromJust ) | |
data Formula = Var String | And Formula Formula | | |
Or Formula Formula | Not Formula | |
getVarsDup (Var v) = [v] | |
getVarsDup (And f1 f2) = (getVarsDup f1) ++ (getVarsDup f2) | |
getVarsDup (Or f1 f2) = (getVarsDup f1) ++ (getVarsDup f2) | |
getVarsDup (Not f) = getVarsDup f | |
genValues n = genAux $ [replicate n True] | |
where genAux (v:vs) = if not $ or $ v then v:vs | |
else genAux ((next v) : v : vs) | |
next (True : ts) = (False : ts) | |
next (False : ts) = (True : (next ts)) | |
solveFormula (Var v) env = fromJust $ lookup v env | |
solveFormula (And f1 f2) env = (solveFormula f1 env) && (solveFormula f2 env) | |
solveFormula (Or f1 f2) env = (solveFormula f1 env) || (solveFormula f2 env) | |
solveFormula (Not f) env = not $ solveFormula f env | |
allSolutions f = map (solveFormula f) (map (zip vars) vals) | |
where vars = nub $ getVarsDup f | |
vals = genValues (length vars) | |
-- solve the SAT problem | |
sat f = or $ allSolutions f | |
-- pointfree! | |
sat2 = or . allSolutions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment