How to resolve the algorithm Parsing/RPN to infix conversion step by step in the REXX programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Parsing/RPN to infix conversion step by step in the REXX programming language
Table of Contents
Problem Statement
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Parsing/RPN to infix conversion step by step in the REXX programming language
Source code in the rexx programming language
/*REXX program converts Reverse Polish Notation (RPN) ───► an infix notation. */
showAction = 1 /* 0 if no showActions wanted. */
# = 0 /*initialize stack pointer to 0 (zero).*/
oS = '+ - / * ^' /*the operator symbols. */
oP = '2 2 3 3 4' /*the operator priorities. */
oA = '◄ ◄ ◄ ◄ ►' /*the operator associations. */
say "infix: " toInfix( "3 4 2 * 1 5 - 2 3 ^ ^ / +" )
say "infix: " toInfix( "1 2 + 3 4 + ^ 5 6 + ^" ) /* [↓] Sprechen Sie Deutsch? */
say "infix: " toInfix( "Mond Sterne Schlamm + * Feur Suppe * ^" )
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
pop: pop= #; #= # - 1; return @.pop
push: #= # + 1; @.#= arg(1); return
/*──────────────────────────────────────────────────────────────────────────────────────*/
stack2str: $=; do j=1 for #; _ = @.j; y= left(_, 1)
if pos(' ', _)==0 then _ = '{'strip( substr(_, 2) )"}"
else _ = substr(_, 2)
$=$ '{'strip(y _)"}"
end /*j*/
return space($)
/*──────────────────────────────────────────────────────────────────────────────────────*/
toInfix: parse arg rpn; say copies('─', 80 - 1); say 'RPN: ' space(rpn)
do N=1 for words(RPN) /*process each of the RPN tokens.*/
?= word(RPN, N) /*obtain next item in the list. */
if pos(?,oS)==0 then call push '¥' ? /*when in doubt, add a Yen to it.*/
else do; g= pop(); gp= left(g, 1); g= substr(g, 2)
h= pop(); hp= left(h, 1); h= substr(h, 2)
tp= substr(oP, pos(?, oS), 1)
ta= substr(oA, pos(?, oS), 1)
if hp
if gp
call push tp || h ? g
end
if showAction then say right(?, 25) "──►" stack2str()
end /*N*/
return space( substr( pop(), 2) )
You may also check:How to resolve the algorithm Semiprime step by step in the Phix programming language
You may also check:How to resolve the algorithm Roots of a function step by step in the Java programming language
You may also check:How to resolve the algorithm Dice game probabilities step by step in the Python programming language
You may also check:How to resolve the algorithm Problem of Apollonius step by step in the Sidef programming language
You may also check:How to resolve the algorithm Idiomatically determine all the characters that can be used for symbols step by step in the Java programming language