module Data.Logic.Propositional.Tables
( truthTable
, truthTableP
) where
import Data.Logic.Propositional.Core
import Data.Map (fold)
import Text.PrettyPrint.ANSI.Leijen (green, text, red)
truthTable :: Expr -> String
truthTable = truthTableP show
truthTableP :: (Expr -> String) -> Expr -> String
truthTableP printer expr = unlines [header, separator, body]
where
header = unwords vs ++ " | " ++ printer expr
body = init . unlines $ map (showAssignment expr) as
separator = concat $ replicate sepLength "-"
sepLength = length vs * 2 + length (printer expr) + 2
as = assignments expr
vs = variables expr
showAssignment :: Expr -> Mapping -> String
showAssignment expr a = showVarValues ++ " | " ++ showExprValue
where
showVarValues = unwords $ fold ((:) . showBool) [] a
showExprValue = showBool $ interpret expr a
showBool :: Bool -> String
showBool True = show . green . text $ "T"
showBool False = show . red . text $ "F"