Arithmetic evaluation: Difference between revisions

Content added Content deleted
m (→‎{{header|Tailspin}}: simplify typing)
(→‎{{header|Tailspin}}: Simplify to use left recursion)
Line 6,114: Line 6,114:
data binaryExpression <{left: <node>, op: <?($ops <[<=$>]>)>, right: <node>}>
data binaryExpression <{left: <node>, op: <?($ops <[<=$>]>)>, right: <node>}>
data node <binaryExpression|"1">
data node <binaryExpression|"1">

templates leftAssociate
when <[](1)> do $(1) !
otherwise [ { left: $(1), op: $(2), right: $(3)}, $(4..last)...] -> #
end leftAssociate


composer parseArithmetic
composer parseArithmetic
(<WS>?) <addition|multiplication|term> (<WS>?)
(<WS>?) <addition|multiplication|term> (<WS>?)
rule addition: [<multiplication|term> <addedTerm>+ ] -> leftAssociate
rule addition: {left:<addition|multiplication|term> (<WS>?) op:<'[+-]'> (<WS>?) right:<multiplication|term>}
rule addedTerm: (<WS>?) <'[+-]'> (<WS>?) <multiplication|term>
rule multiplication: {left:<multiplication|term> (<WS>?) op:<'[*/]'> (<WS>?) right:<term>}
rule multiplication: [<term> <multipliedTerm>+] -> leftAssociate
rule multipliedTerm: (<WS>?) <'[*/]'> (<WS>?) <term>
rule term: <INT|parentheses>
rule term: <INT|parentheses>
rule parentheses: (<'\('> <WS>?) <addition|multiplication|term> (<WS>? <'\)'>)
rule parentheses: (<'\('> <WS>?) <addition|multiplication|term> (<WS>? <'\)'>)
Line 6,156: Line 6,149:
composer calculator
composer calculator
(<WS>?) <addition|multiplication|term> (<WS>?)
(<WS>?) <addition|multiplication|term> (<WS>?)
rule addition: [<multiplication|term> <addedTerm>+ ] ->
rule addition: [<addition|multiplication|term> (<WS>?) <'[+-]'> (<WS>?) <multiplication|term>] ->
\(when <[](1)> $(1) !
\(when <?($(2) <='+'>)> do $(1) + $(3) !
when <?($(2) <='+'>)> do [ $(1) + $(3), $(4..last)...] -> #
otherwise $(1) - $(3) !
otherwise [ $(1) - $(3), $(4..last)...] -> #
\)
\)
rule addedTerm: (<WS>?) <'[+-]'> (<WS>?) <multiplication|term>
rule multiplication: [<multiplication|term> (<WS>?) <'[*/]'> (<WS>?) <term>] ->
\(when <?($(2) <='*'>)> do $(1) * $(3) !
rule multiplication: [<term> <multipliedTerm>+] ->
\(when <[](1)> $(1) !
otherwise $(1) ~/ $(3) !
when <?($(2) <='*'>)> do [ $(1) * $(3), $(4..last)...] -> #
otherwise [ $(1) ~/ $(3), $(4..last)...] -> #
\)
\)
rule multipliedTerm: (<WS>?) <'[*/]'> (<WS>?) <term>
rule term: <INT|parentheses>
rule term: <INT|parentheses>
rule parentheses: (<'\('> <WS>?) <addition|multiplication|term> (<WS>? <'\)'>)
rule parentheses: (<'\('> <WS>?) <addition|multiplication|term> (<WS>? <'\)'>)