Arithmetic evaluation: Difference between revisions

Added Tailspin solution
(Added Tailspin solution)
Line 5,977:
(exp, nil) => eval exp
| _ => raise Error "not parseable stuff at the end"</lang>
 
=={{header|Tailspin}}==
<lang tailspin>
templates variadicToBinary
when <[](1)> $(1) !
otherwise [ { left: $(1), op: $(2), right: $(3)}, $(4..last)...] -> #
end variadicToBinary
 
composer parseArithmetic
(<WS>?) <addition|multiplication|term> (<WS>?)
rule addition: [<multiplication|term> <addedTerm>+ ] -> variadicToBinary
rule addedTerm: (<WS>?) <'[+-]'> (<WS>?) <multiplication|term>
rule multiplication: [<term> <multipliedTerm>+] -> variadicToBinary
rule multipliedTerm: (<WS>?) <'[*/]'> (<WS>?) <term>
rule term: <INT|parentheses>
rule parentheses: (<'\('> <WS>?) <addition|multiplication|term> (<WS>? <'\)'>)
end parseArithmetic
 
templates evaluateArithmetic
<{op: <='+'>}> ($.left -> evaluateArithmetic) + ($.right -> evaluateArithmetic) !
<{op: <='-'>}> ($.left -> evaluateArithmetic) - ($.right -> evaluateArithmetic) !
<{op: <='*'>}> ($.left -> evaluateArithmetic) * ($.right -> evaluateArithmetic) !
<{op: <='/'>}> ($.left -> evaluateArithmetic) ~/ ($.right -> evaluateArithmetic) !
<> $ !
end evaluateArithmetic
 
def ast: '(100 - 5 * (2+3*4) + 2) / 2' -> parseArithmetic;
 
'$ast;
' -> !OUT::write
 
'$ast -> evaluateArithmetic;
' -> !OUT::write
</lang>
{{out}}
<pre>
{left={left={left=100, op=-, right={left=5, op=*, right={left=2, op=+, right={left=3, op=*, right=4}}}}, op=+, right=2}, op=/, right=2}
16
</pre>
 
=={{header|Tcl}}==
Anonymous user