Runtime evaluation/In an environment: Difference between revisions

→‎{{header|Python}}: alternate implementation using compile & introspection
(→‎{{header|Python}}: alternate implementation using compile & introspection)
Line 59:
x[1]: 5
f(3) = 8; f(5) = 32; f(5) - f(3) = 24</lang>
 
===Python using introspection===
In Python, one can compile an expression then query the compiled object to find out the names that are used. This second example uses this method:
<lang python>func = compile( raw_input('Enter expression: '),
'compile_error.txt',
'eval' )
# ask for two sets of any names used in the expression
name = [{}, {}]
for n in func.co_names: name[0][n] = input('First value of %s: ' % n)
for n in func.co_names: name[1][n] = input('Second value of %s: ' % n)
 
print "\n<Expression at second value set> - <Expression at first> =", \
eval(func, name[1]) - eval(func, name[0])
</lang>
A simple use would be:
<lang python>Enter expression: 2**x
First value of x: 3
Second value of x: 5
 
<Expression at second value set> - <Expression at first> = 24</lang>
and for an initial expression using multiple variables:
<lang python>Enter expression: 3 * x + y
First value of x: 1
First value of y: 2
Second value of x: 3
Second value of y: 4
 
<Expression at second value set> - <Expression at first> = 8</lang>
 
=={{header|Ruby}}==
Anonymous user