Skip to content

Instantly share code, notes, and snippets.

@joedougherty
Last active July 11, 2018 04:00
Show Gist options
  • Save joedougherty/bc8714cf14898b30951ec1b67345efef to your computer and use it in GitHub Desktop.
Save joedougherty/bc8714cf14898b30951ec1b67345efef to your computer and use it in GitHub Desktop.
Parse sentential logic w/Parsimonious
# -*- coding: utf-8 -*-
from parsimonious.grammar import Grammar
try:
from string import lowercase
except:
from string import ascii_lowercase as lowercase
def vars_expr():
"""
Generate a string to match all vars (except for "v" -- this is used to denote logical or):
"a" / "b" / "c" / "d" / "e" / "f" (etc.)
"""
variables = ['"{}"'.format(l) for l in lowercase if l != 'v']
return ' / '.join(variables)
g = Grammar(
"""
EXPR = NEG* OPENPAREN OPERAND SPACE BINOP SPACE OPERAND CLOSEPAREN
# Character Classes
SPACE = " "
NEG = "~" / "!" / "¬"
OPENPAREN = "("
VAR = {}
CLOSEPAREN = ")"
BINOP = "v" / "&" / "=" / "<->" / "->" / "or"
# Character Class Combinations
OPERAND = TERM / EXPR
TERM = NEG* VAR
""".format(vars_expr()))
g.parse('''!(p & q)''')
g.parse('''!(p v (r -> s))''')
g.parse('''((p v w) <-> !e)''')
g.parse('''((p v !w) & (l <-> x))''')
g.parse('''(p <-> ~(!q -> (r v s)))''')
g.parse('''(p or ~(!q -> (r v s)))''')
g.parse('''!¬(p v ~!~q)''')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment