Skip to content

Instantly share code, notes, and snippets.

@ncaq
Created August 19, 2017 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncaq/e387ffb82c5b080a78892ac3da81606c to your computer and use it in GitHub Desktop.
Save ncaq/e387ffb82c5b080a78892ac3da81606c to your computer and use it in GitHub Desktop.
途中まで書いた論理式処理系
import Control.Monad.Trans.Reader
import qualified Data.Map as M
import Data.Maybe
import Text.ParserCombinators.Parsec
data PropForm = PropFormSymbol String | PropNot PropForm | PropFormImplies PropForm PropForm
deriving (Show, Read)
readPropForm :: String -> Either ParseError PropForm
readPropForm = parse parsePropForm "propForm"
parsePropForm :: Parser PropForm
parsePropForm = do
prefixNot <- (char '!' >> pure PropNot) <|> pure id
prefix <- prefixNot <$> parseSymbol
parseImplies prefix <|> pure prefix
parseImplies :: PropForm -> Parser PropForm
parseImplies prefix = PropFormImplies prefix <$ string "->" <* spaces <*> parsePropForm <* spaces
parseSymbol :: Parser PropForm
parseSymbol = PropFormSymbol <$> many alphaNum <* spaces
execPropForm :: String -> [(String, Bool)] -> Bool
execPropForm propString env = let Right propForm = readPropForm propString
in runReader (evalPropForm propForm) (M.fromList env)
evalPropForm :: PropForm -> Reader (M.Map String Bool) Bool
evalPropForm (PropFormSymbol symbolName) = fromJust . M.lookup symbolName <$> ask
evalPropForm (PropNot prop) = not <$> evalPropForm prop
evalPropForm (PropFormImplies prefix suffix) = implies <$>
evalPropForm prefix <*> evalPropForm suffix
implies :: Bool -> Bool -> Bool
implies a b = not a || b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment