Skip to content

Instantly share code, notes, and snippets.

@tautologico
Created April 28, 2011 01:04
Show Gist options
  • Save tautologico/945597 to your computer and use it in GitHub Desktop.
Save tautologico/945597 to your computer and use it in GitHub Desktop.
Calculating truth tables for propositional formulas
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