Skip to content

Instantly share code, notes, and snippets.

@calroc
Created March 4, 2013 08:36
Show Gist options
  • Save calroc/5080869 to your computer and use it in GitHub Desktop.
Save calroc/5080869 to your computer and use it in GitHub Desktop.
Driving the LogPy logic package using a simple Omega parser. I'm probably being silly and naive, but it's fun. https://github.com/logpy/logpy https://gitorious.org/python-omega/
#!/usr/bin/env python
from omega import BaseParser
from logpy import run, eq, membero, var, conde
# Still TODO: membero and conde
#: Namespace for storing logic variable as they are defined.
variables = {}
def define(name, namespace=variables):
'''
Return a named logic variable in the namespace.
'''
return namespace.setdefault(name, var(name))
def _run(n, t, *eqs):
'''Occasionally it's nice to look at the eqs.'''
print eqs
return run(n, t, *eqs)
class LogicParser(BaseParser):
__grammar = '''
# Cribbed "spaces" rule from omega.bootstrap.OmegaParser
spaces = (' ' | '\r' | '\n' | '\t')* -> ' ' ;
digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ;
digits = digit+:ds -> ("".join(ds));
optional_digits = digit*:ds -> ("".join(ds));
number = digits:i '.' optional_digits:f -> (float(i + '.' + f)) |
'.' digits:f -> (float('.' + f)) |
digits:i -> (int(i)) ;
char = anything:ch ?('a' <= ch <= 'z') -> (ch) ;
variable = char+:chs -> (define(''.join(chs))) ;
group = '(' termite+:T ')' -> (tuple(T)) ;
termite = ' '* (group | variable | number) ;
EQ = spaces termite:a ' '* "=" termite:b -> ((eq, a, b)) ;
query = spaces variable:x ' '* "?" -> (x) ;
logic = EQ*:eqs query:x spaces -> (run(0, x, *eqs)) ;
'''
if __name__ == '__main__':
print (23.2,) == LogicParser.match('''
a = b
a = 23.2
b?
''')
print (2.0,) == LogicParser.match('''
a = b
2. = a
b?
''')
print (0.23,) == LogicParser.match('''
b = a
a = .23
b?
''')
print (1,) == LogicParser.match('''
(b 2) = (1 2)
b?
''')
print (2,) == LogicParser.match('''
(1 b 3) = (1 2 3)
b?
''')
print (2,) == LogicParser.match('''
(1 (a 3)) = (1 (2 3))
a ?
''')
print ((1, 3),) == LogicParser.match('''
b = (1 3)
(1 (a 3)) = (1 (b 3))
a?
''')
print (2,) == LogicParser.match('''
b = (2 3)
(1 (a 3)) = (1 b)
a?
''')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment