Arithmetic evaluation: Difference between revisions

→‎{{header|Tcl}}: renamed 'arieval' to the clearer 'ast'
(→‎{{header|Tcl}}: use 'in' operator)
(→‎{{header|Tcl}}: renamed 'arieval' to the clearer 'ast')
Line 1,452:
<lang Tcl>namespace import tcl::mathop::*
 
proc arievalast str {
# produce abstract syntax tree for an expression
regsub -all {[-+*/()]} $str { & } str ;# "tokenizer"
Line 1,485:
#-- Test suite
foreach test [split {
arievalast 2-2
arievalast 1-2-3
arievalast (1-2)-3
arievalast 1-(2-3)
arievalast (1+2)*3
arievalast (1+2)/3-4*5
arievalast ((1+2)/3-4)*5
} \n] {
puts "$test ..... [eval $test] ..... [eval [eval $test]]"
}</lang>
Output:<pre>
arievalast 2-2 ..... - 2 2 ..... 0
arievalast 1-2-3 ..... - [- 1 2] 3 ..... -4
arievalast (1-2)-3 ..... - [- 1 2] 3 ..... -4
arievalast 1-(2-3) ..... - 1 [- 2 3] ..... 2
arievalast (1+2)*3 ..... * [+ 1 2] 3 ..... 9
arievalast (1+2)/3-4*5 ..... - [/ [+ 1 2] 3] [* 4 5] ..... -19
arievalast ((1+2)/3-4)*5 ..... * [- [/ [+ 1 2] 3] 4] 5 ..... -15
</pre>
Anonymous user