Skip to content

Commit

Permalink
Fixed calc in examples
Browse files Browse the repository at this point in the history
  • Loading branch information
erezsh committed Nov 17, 2012
1 parent 59c09d4 commit f9ed8ee
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 205 deletions.
79 changes: 22 additions & 57 deletions examples/calc.py
@@ -1,64 +1,39 @@
import sys, os # calc.py - # A simple calculator without using eval
sys.path.append('..') # A shorter and simpler re-implementation of http://www.dabeaz.com/ply/example.html


from pprint import pprint import operator as op
from operator import itemgetter, add, sub, mul, div, neg from plyplus import Grammar, STransformer

from plyplus import Grammar
from sexp import Transformer


calc_grammar = Grammar(""" calc_grammar = Grammar("""
start: expression; start: add;
@expression: bin_op | un_op | parenthesis | number ;
parenthesis: '\(' expression '\)'; ?add: (add add_symbol)? mul;
bin_op: expression ('\+'|'-'|'\*'|'/') expression; ?mul: (mul mul_symbol)? atom;
un_op: '-' expression; @atom: neg | number | '\(' add '\)';
neg: '-' atom;
number: '[\d.]+'; number: '[\d.]+';
PLUS: '\+'; mul_symbol: '\*' | '/';
MINUS: '-'; add_symbol: '\+' | '-';
MUL: '\*';
DIV: '/';
WS: '[ \t]+' (%ignore); WS: '[ \t]+' (%ignore);
###
self.precedence = (
('left','PLUS','MINUS'),
('left','MUL','DIV'),
)
""") """)


class Calc(Transformer): class Calc(STransformer):
unary_operator_mapping = {
'-': neg,
}

bin_operator_mapping = {
'+': add,
'-': sub,
'*': mul,
'/': div,
}


start = itemgetter(1) # start only has one member: expression def _bin_operator(self, exp):
parenthesis = itemgetter(2) # get the expression between the parenthesis arg1, operator_symbol, arg2 = exp.tail


def number(self, exp): operator_func = { '+': op.add, '-': op.sub, '*': op.mul, '/': op.div }[operator_symbol]
return float(exp[1])


def un_op(self, exp): return operator_func(arg1, arg2)
_, operator_symbol, arg = exp


operator = self.unary_operator_mapping[operator_symbol] number = lambda self, exp: float(exp.tail[0])
return operator(arg) neg = lambda self, exp: -exp.tail[0]

__default__ = lambda self, exp: exp.tail[0]
def bin_op(self, exp):
_, arg1, operator_symbol, arg2 = exp

operator = self.bin_operator_mapping[operator_symbol]
return operator(arg1, arg2)


add = _bin_operator
mul = _bin_operator


def main(): def main():
calc = Calc() calc = Calc()
Expand All @@ -72,14 +47,4 @@ def main():
tree = calc_grammar.parse(s) tree = calc_grammar.parse(s)
print calc.transform(tree) print calc.transform(tree)


def _test():
s="4.5-2+3*(-1/-2)"
tree = calc_grammar.parse(s)
pprint(tree)
res = Calc().transform(tree)
print s,"=",res
assert res == 4


#_test()
main() main()
85 changes: 0 additions & 85 deletions examples/calc2.py

This file was deleted.

63 changes: 0 additions & 63 deletions examples/calc3.py

This file was deleted.

0 comments on commit f9ed8ee

Please sign in to comment.