Runtime evaluation/In an environment: Difference between revisions

→‎{{header|Tcl}}: provide another solution for clarified requirements
(→‎{{header|Octave}}: add note about nonglobalness)
(→‎{{header|Tcl}}: provide another solution for clarified requirements)
Line 176:
 
=={{header|Tcl}}==
<lang tcl>proc eval_twice {func a b} {
 
<lang tcl>package require Tcl 8.5
 
proc eval_twice {func a b} {
set x $a
set 1st [expr $func];
set x $b
set 2nd [expr $func];
expr {$2nd - $1st}
}
 
puts [eval_twice {2 ** $x} 3 5] ;# ==> 24</lang>
 
Here's another take, similar to other answers. It passes a code block to be <code>eval</code>ed, not just an expression for <code>expr</code>
<lang tcl>proc eval_with_x {code val1 val2} {
expr {[set x $val2; eval $code] - [set x $val1; eval $code]}
}
eval_with_x {expr {2**$x}} 3 5 ;# ==> 24</lang>
Anonymous user