Arithmetic evaluation: Difference between revisions

m
→‎{{header|Python}}: ast standard library module
(C LL(1) Recursive Descent parser)
m (→‎{{header|Python}}: ast standard library module)
Line 1,770:
astTree = Lex( expr, Yaccer())
print expr, '=',astTree.eval()</lang>
 
===ast standard library module===
Python comes with its own [http://docs.python.org/3.1/library/ast.html#module-ast ast] module as part of its standard libraries. The module compiles Python source into an AST tree that can in turn be compiled then be executed.
<lang python>>>> import ast
>>>
>>> expr="2 * (3 -1) + 2 * 5"
>>> node = ast.parse(expr, mode='eval')
>>> ast.dump(node)
'Expression(body=BinOp(left=BinOp(left=Num(n=2), op=Mult(), right=BinOp(left=Num(n=3), op=Sub(), right=Num(n=1))), op=Add(), right=BinOp(left=Num(n=2), op=Mult(), right=Num(n=5))))'
>>> code_object = compile(node, filename='<string>', mode='eval')
>>> eval(code_object)
14</lang>
 
=={{header|Tcl}}==
Anonymous user