⚠️ Warning: This is a draft ⚠️
This means it might contain formatting issues,
incorrect code, conceptual problems, or other severe issues.
If you want to help to improve and eventually enable this page,
please fork
RosettaGit's repository
and open a merge request on GitHub.
{{clarified-review}}
{{task}}
;Task:
Create a program that takes an [[wp:Reverse Polish notation|RPN]] representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in [[wp:Infix notation|infix notation]].
-
Assume an input of a correct, space separated, string of tokens
-
Generate a space separated output string representing the same expression in infix notation
-
Show how the major datastructure of your algorithm changes with each new token parsed.
-
Test with the following input RPN strings then print and display the output here.
:{| class="wikitable"
! RPN input !! sample output
|- || align="center"
| 3 4 2 * 1 5 - 2 3 ^ ^ / +
|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
|- || align="center"
| 1 2 + 3 4 + ^ 5 6 + ^
|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
|}
-
Operator precedence and operator associativity is given in this table:
:{| class="wikitable"
! operator !! [[wp:Order_of_operations|precedence]] !! [[wp:Operator_associativity|associativity]] !! operation
|- || align="center"
| ^ || 4 || right || exponentiation
|- || align="center"
| * || 3 || left || multiplication
|- || align="center"
| / || 3 || left || division
|- || align="center"
| + || 2 || left || addition
|- || align="center"
| - || 2 || left || subtraction
|}
;See also:
- [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
- [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
- [http://www.rubyquiz.com/quiz148.html Postfix to infix] from the RubyQuiz site.
Ada
Using the solution of the task [[stack]]:
type Priority is range 1..4;
type Infix is record
Precedence : Priority;
Expression : Unbounded_String;
end record;
package Expression_Stack is new Generic_Stack (Infix);
use Expression_Stack;
function Convert (RPN : String) return String is
Arguments : Stack;
procedure Pop
( Operation : Character;
Precedence : Priority;
Association : Priority
) is
Right, Left : Infix;
Result : Infix;
begin
Pop (Right, Arguments);
Pop (Left, Arguments);
Result.Precedence := Association;
if Left.Precedence < Precedence then
Append (Result.Expression, '(');
Append (Result.Expression, Left.Expression);
Append (Result.Expression, ')');
else
Append (Result.Expression, Left.Expression);
end if;
Append (Result.Expression, ' ');
Append (Result.Expression, Operation);
Append (Result.Expression, ' ');
if Right.Precedence < Precedence then
Append (Result.Expression, '(');
Append (Result.Expression, Right.Expression);
Append (Result.Expression, ')');
else
Append (Result.Expression, Right.Expression);
end if;
Push (Result, Arguments);
end Pop;
Pointer : Integer := RPN'First;
begin
while Pointer <= RPN'Last loop
case RPN (Pointer) is
when ' ' =>
Pointer := Pointer + 1;
when '0'..'9' =>
declare
Start : constant Integer := Pointer;
begin
loop
Pointer := Pointer + 1;
exit when Pointer > RPN'Last
or else RPN (Pointer) not in '0'..'9';
end loop;
Push
( ( 4,
To_Unbounded_String (RPN (Start..Pointer - 1))
),
Arguments
);
end;
when '+' | '-' =>
Pop (RPN (Pointer), 1, 1);
Pointer := Pointer + 1;
when '*' | '/' =>
Pop (RPN (Pointer), 2, 2);
Pointer := Pointer + 1;
when '^' =>
Pop (RPN (Pointer), 4, 3);
Pointer := Pointer + 1;
when others =>
raise Constraint_Error with "Syntax";
end case;
end loop;
declare
Result : Infix;
begin
Pop (Result, Arguments);
return To_String (Result.Expression);
end;
end Convert;
The test program:
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
with Generic_Stack;
procedure RPN_to_Infix is
-- The code above
begin
Put_Line ("3 4 2 * 1 5 - 2 3 ^ ^ / + = ");
Put_Line (Convert ("3 4 2 * 1 5 - 2 3 ^ ^ / +"));
Put_Line ("1 2 + 3 4 + ^ 5 6 + ^ = ");
Put_Line (Convert ("1 2 + 3 4 + ^ 5 6 + ^"));
end RPN_to_Infix;
should produce the following output
3 4 2 * 1 5 - 2 3 ^ ^ / + =
3 + 4 * 2 / (1 - 5) ^ (2 ^ 3)
1 2 + 3 4 + ^ 5 6 + ^ =
((1 + 2) ^ (3 + 4)) ^ (5 + 6)
ALGOL 68
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
Recursively parses the RPN string backwards to build a parse tree which is then printed.
# rpn to infix - parses an RPN expression and generates the equivalent #
# infix expression #
PROC rpn to infix = ( STRING rpn )STRING:
BEGIN
# we parse the string backwards using recursive descent #
INT rpn pos := UPB rpn;
BOOL had error := FALSE;
# mode to hold nodes of the parse tree #
MODE NODE = STRUCT( INT op
, UNION( REF NODE, STRING ) left
, REF NODE right
);
REF NODE nil node = NIL;
# op codes #
INT error = 1;
INT factor = 2;
INT add = 3;
INT sub = 4;
INT mul = 5;
INT div = 6;
INT pwr = 7;
[]STRING op name = ( "error", "factor", "+", "-", "*", "/", "^" );
[]BOOL right associative
= ( FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE );
[]INT priority = ( 1, 1, 2, 2, 3, 3, 4 );
# returns TRUE if we have reached the end of the rpn string, #
# FALSE otherwise #
PROC at end = BOOL: rpn pos < LWB rpn;
# positions to the previous character, if there is one #
PROC next = VOID: rpn pos -:= 1;
# skip spaces in the rpn string #
PROC skip spaces = VOID:
WHILE have( " " )
DO
next
OD # skip spaces # ;
# returns TRUE if the rpn character at rpn pos is c, #
# FALSE if the character is not c or there is no character #
# at rpn pos #
PROC have = ( CHAR c )BOOL:
IF at end
THEN
# no character at rpn pos #
FALSE
ELSE
# have a character - check it is the required one #
rpn[ rpn pos ] = c
FI # have # ;
# gets an operand from the rpn string #
# an operand is either a number or a sub-expression #
PROC get operand = ( STRING rpn, STRING operand name )REF NODE:
BEGIN
# handle the operator or operand, if there is one #
skip spaces;
print( ( ( "parsing "
+ operand name
+ " from: "
+ IF at end THEN "" ELSE rpn[ LWB rpn : rpn pos ] FI
)
, newline
)
);
REF NODE result :=
IF at end
THEN
# no operand #
had error := TRUE;
HEAP NODE := ( error, "!! Missing operand !!", NIL )
ELIF have( "+" )
THEN
# addition #
next;
HEAP NODE right := get operand( rpn, "+ right operand" );
HEAP NODE left := get operand( rpn, "+ left operand" );
HEAP NODE := ( add, left, right )
ELIF have( "-" )
THEN
# subtraction #
next;
HEAP NODE right := get operand( rpn, "- right operand" );
HEAP NODE left := get operand( rpn, "- left operand" );
HEAP NODE := ( sub, left, right )
ELIF have( "*" )
THEN
# multiplication #
next;
HEAP NODE right := get operand( rpn, "* right operand" );
HEAP NODE left := get operand( rpn, "* left operand" );
HEAP NODE := ( mul, left, right )
ELIF have( "/" )
THEN
# division #
next;
HEAP NODE right := get operand( rpn, "/ right operand" );
HEAP NODE left := get operand( rpn, "/ left operand" );
HEAP NODE := ( div, left, right )
ELIF have( "^" )
THEN
# exponentiation #
next;
HEAP NODE right := get operand( rpn, "^ right operand" );
HEAP NODE left := get operand( rpn, "^ left operand" );
HEAP NODE := ( pwr, left, right )
ELSE
# must be an operand #
STRING value := "";
WHILE NOT at end
AND NOT have( " " )
DO
rpn[ rpn pos ] +=: value;
next
OD;
HEAP NODE := ( factor, value, NIL )
FI;
print( ( operand name + ": " + TOSTRING result, newline ) );
result
END # get operand # ;
# converts the parse tree to a string with apppropriate parenthesis #
OP TOSTRING = ( REF NODE operand )STRING:
BEGIN
# converts a node of the parse tree to a string, inserting #
# parenthesis if necessary #
PROC possible parenthesis = ( INT op, REF NODE expr )STRING:
IF op OF expr = error
OR op OF expr = factor
THEN
# operand is an error/factor - parenthisis not needed #
TOSTRING expr
ELIF priority( op OF expr ) < priority( op )
THEN
# the expression is a higher precedence operator than the #
# one we are building the expression for - need parenthesis #
( "( " + TOSTRING expr + " )" )
ELIF right associative[ op OF operand ]
AND op OF left( operand ) = op OF operand
THEN
# right associative operator #
( "( " + TOSTRING expr + " )" )
ELSE
# lower precedence expression - parenthesis not needed #
TOSTRING expr
FI # possible parenthesis # ;
# gets the left branch of a node, which must be a node #
PROC left = ( REF NODE operand )REF NODE:
CASE left OF operand
IN ( REF NODE o ): o
, ( STRING s ): HEAP NODE := ( error, s, NIL )
ESAC # left # ;
IF had error
THEN
# an error occured parsing the expression #
"Invalid expression"
ELIF operand IS nil node
THEN
# no operand? #
"<empty>"
ELIF op OF operand = error
OR op OF operand = factor
THEN
# error parsing the expression #
# or a factor #
CASE left OF operand
IN ( REF NODE o ): "Error: String expected: (" + TOSTRING o + ")"
, ( STRING s ): s
ESAC
ELSE
# general operand #
( possible parenthesis( op OF operand, left( operand ) )
+ " " + op name[ op OF operand ] + " "
+ possible parenthesis( op OF operand, right OF operand )
)
FI
END # TOSTRING # ;
STRING result = TOSTRING get operand( rpn, "expression" );
# ensure there are no more tokens in the string #
skip spaces;
IF at end
THEN
# OK - there was only one expression #
result
ELSE
# extraneous tokens #
( "Error - unexpected text before expression: ("
+ rpn[ LWB rpn : rpn pos ]
+ ")"
)
FI
END # rpn to infix # ;
main: (
# test the RPN to Infix comnverter #
STRING rpn;
rpn := "3 4 2 * 1 5 - 2 3 ^ ^ / +";
print( ( rpn, ": ", rpn to infix( rpn ), newline, newline ) );
rpn := "1 2 + 3 4 + ^ 5 6 + ^";
print( ( rpn, ": ", rpn to infix( rpn ), newline ) )
)
{{out}}
parsing expression from: 3 4 2 * 1 5 - 2 3 ^ ^ / +
parsing + right operand from: 3 4 2 * 1 5 - 2 3 ^ ^ /
parsing / right operand from: 3 4 2 * 1 5 - 2 3 ^ ^
parsing ^ right operand from: 3 4 2 * 1 5 - 2 3 ^
parsing ^ right operand from: 3 4 2 * 1 5 - 2 3
^ right operand: 3
parsing ^ left operand from: 3 4 2 * 1 5 - 2
^ left operand: 2
^ right operand: 2 ^ 3
parsing ^ left operand from: 3 4 2 * 1 5 -
parsing - right operand from: 3 4 2 * 1 5
- right operand: 5
parsing - left operand from: 3 4 2 * 1
- left operand: 1
^ left operand: 1 - 5
/ right operand: ( 1 - 5 ) ^ 2 ^ 3
parsing / left operand from: 3 4 2 *
parsing * right operand from: 3 4 2
* right operand: 2
parsing * left operand from: 3 4
* left operand: 4
/ left operand: 4 * 2
+ right operand: 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
parsing + left operand from: 3
+ left operand: 3
expression: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
3 4 2 * 1 5 - 2 3 ^ ^ / +: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
parsing expression from: 1 2 + 3 4 + ^ 5 6 + ^
parsing ^ right operand from: 1 2 + 3 4 + ^ 5 6 +
parsing + right operand from: 1 2 + 3 4 + ^ 5 6
+ right operand: 6
parsing + left operand from: 1 2 + 3 4 + ^ 5
+ left operand: 5
^ right operand: 5 + 6
parsing ^ left operand from: 1 2 + 3 4 + ^
parsing ^ right operand from: 1 2 + 3 4 +
parsing + right operand from: 1 2 + 3 4
+ right operand: 4
parsing + left operand from: 1 2 + 3
+ left operand: 3
^ right operand: 3 + 4
parsing ^ left operand from: 1 2 +
parsing + right operand from: 1 2
+ right operand: 2
parsing + left operand from: 1
+ left operand: 1
^ left operand: 1 + 2
^ left operand: ( 1 + 2 ) ^ ( 3 + 4 )
expression: ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
1 2 + 3 4 + ^ 5 6 + ^: ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
AWK
Slavishly (mostly) follows TCL example, but instead of lists it uses strings. Except for the stack, which uses an array, of course.
The kludge is prepending the precedence on the front of the expressions stored on the stack. This shows up when the tail() function is used, and when 'x' is prepended as a placeholder when adding parenthesis.
#!/usr/bin/awk -f
BEGIN {
initStack()
initOpers()
print "Infix: " toInfix("3 4 2 * 1 5 - 2 3 ^ ^ / +")
print ""
print "Infix: " toInfix("1 2 + 3 4 + ^ 5 6 + ^")
print ""
print "Infix: " toInfix("moon stars mud + * fire soup * ^")
exit
}
function initStack() {
delete stack
stackPtr = 0
}
function initOpers() {
VALPREC = "9"
LEFT = "l"
RIGHT = "r"
operToks = "+" "-" "/" "*" "^"
operPrec = "2" "2" "3" "3" "4"
operAssoc = LEFT LEFT LEFT LEFT RIGHT
}
function toInfix(rpn, t, toks, tok, a, ap, b, bp, tp, ta) {
print "Postfix: " rpn
split(rpn, toks, / +/)
for (t = 1; t <= length(toks); t++) {
tok = toks[t]
if (!isOper(tok)) {
push(VALPREC tok)
}
else {
b = pop()
bp = prec(b)
b = tail(b)
a = pop()
ap = prec(a)
a = tail(a)
tp = tokPrec(tok)
ta = tokAssoc(tok)
if (ap < tp || (ap == tp && ta == RIGHT)) {
a = "(" a ")"
}
if (bp < tp || (bp == tp && ta == LEFT)) {
b = "(" b ")"
}
push(tp a " " tok " " b)
}
print " " tok " -> " stackToStr()
}
return tail(pop())
}
function push(expr) {
stack[stackPtr] = expr
stackPtr++
}
function pop() {
stackPtr--
return stack[stackPtr]
}
function isOper(tok) {
return index(operToks, tok) != 0
}
function prec(expr) {
return substr(expr, 1, 1)
}
function tokPrec(tok) {
return substr(operPrec, operIdx(tok), 1)
}
function tokAssoc(tok) {
return substr(operAssoc, operIdx(tok), 1)
}
function operIdx(tok) {
return index(operToks, tok)
}
function tail(s) {
return substr(s, 2)
}
function stackToStr( s, i, t, p) {
s = ""
for (i = 0; i < stackPtr; i++) {
t = stack[i]
p = prec(t)
if (index(t, " ")) t = "{" tail(t) "}"
else t = tail(t)
s = s "{" p " " t "} "
}
return s
}
Output:
Postfix: 3 4 2 * 1 5 - 2 3 ^ ^ / +
3 -> {9 3}
4 -> {9 3} {9 4}
2 -> {9 3} {9 4} {9 2}
* -> {9 3} {3 {4 * 2}}
1 -> {9 3} {3 {4 * 2}} {9 1}
5 -> {9 3} {3 {4 * 2}} {9 1} {9 5}
- -> {9 3} {3 {4 * 2}} {2 {1 - 5}}
2 -> {9 3} {3 {4 * 2}} {2 {1 - 5}} {9 2}
3 -> {9 3} {3 {4 * 2}} {2 {1 - 5}} {9 2} {9 3}
^ -> {9 3} {3 {4 * 2}} {2 {1 - 5}} {4 {2 ^ 3}}
^ -> {9 3} {3 {4 * 2}} {4 {(1 - 5) ^ 2 ^ 3}}
/ -> {9 3} {3 {4 * 2 / (1 - 5) ^ 2 ^ 3}}
+ -> {2 {3 + 4 * 2 / (1 - 5) ^ 2 ^ 3}}
Infix: 3 + 4 * 2 / (1 - 5) ^ 2 ^ 3
Postfix: 1 2 + 3 4 + ^ 5 6 + ^
1 -> {9 1}
2 -> {9 1} {9 2}
+ -> {2 {1 + 2}}
3 -> {2 {1 + 2}} {9 3}
4 -> {2 {1 + 2}} {9 3} {9 4}
+ -> {2 {1 + 2}} {2 {3 + 4}}
^ -> {4 {(1 + 2) ^ (3 + 4)}}
5 -> {4 {(1 + 2) ^ (3 + 4)}} {9 5}
6 -> {4 {(1 + 2) ^ (3 + 4)}} {9 5} {9 6}
+ -> {4 {(1 + 2) ^ (3 + 4)}} {2 {5 + 6}}
^ -> {4 {((1 + 2) ^ (3 + 4)) ^ (5 + 6)}}
Infix: ((1 + 2) ^ (3 + 4)) ^ (5 + 6)
Postfix: moon stars mud + * fire soup * ^
moon -> {9 moon}
stars -> {9 moon} {9 stars}
mud -> {9 moon} {9 stars} {9 mud}
+ -> {9 moon} {2 {stars + mud}}
* -> {3 {moon * (stars + mud)}}
fire -> {3 {moon * (stars + mud)}} {9 fire}
soup -> {3 {moon * (stars + mud)}} {9 fire} {9 soup}
* -> {3 {moon * (stars + mud)}} {3 {fire * soup}}
^ -> {4 {(moon * (stars + mud)) ^ (fire * soup)}}
Infix: (moon * (stars + mud)) ^ (fire * soup)
AutoHotkey
{{works with|AutoHotkey_L}}
expr := "3 4 2 * 1 5 - 2 3 ^ ^ / +"
stack := {push: func("ObjInsert"), pop: func("ObjRemove")}
out := "TOKEN`tACTION STACK (comma separated)`r`n"
Loop Parse, expr, %A_Space%
{
token := A_LoopField
if token is number
stack.push([0, token])
if isOp(token)
{
b := stack.pop(), a := stack.pop(), p := b.1 > a.1 ? b.1 : a.1
p := Precedence(token) > p ? precedence(token) : p
if (a.1 < b.1) and isRight(token)
stack.push([p, "( " . a.2 " ) " token " " b.2])
else if (a.1 > b.1) and isLeft(token)
stack.push([p, a.2 token " ( " b.2 " ) "])
else
stack.push([p, a.2 . " " . token . " " . b.2])
}
out .= token "`t" (isOp(token) ? "Push Partial expression "
: "Push num" space(16)) disp(stack) "`r`n"
}
out .= "`r`n The final output infix expression is: '" disp(stack) "'"
clipboard := out
isOp(t){
return (!!InStr("+-*/^", t) && t)
}
IsLeft(o){
return !!InStr("*/+-", o)
}
IsRight(o){
return o = "^"
}
Precedence(o){
return (InStr("+-/*^", o)+3)//2
}
Disp(obj){
for each, val in obj
if val[2]
o .= ", " val[2]
return SubStr(o,3)
}
Space(n){
return n>0 ? A_Space Space(n-1) : ""
}
;Output
TOKEN ACTION STACK (comma separated)
3 Push num 3
4 Push num 3, 4
2 Push num 3, 4, 2
* Push Partial expression 3, 4 * 2
1 Push num 3, 4 * 2, 1
5 Push num 3, 4 * 2, 1, 5
- Push Partial expression 3, 4 * 2, 1 - 5
2 Push num 3, 4 * 2, 1 - 5, 2
3 Push num 3, 4 * 2, 1 - 5, 2, 3
^ Push Partial expression 3, 4 * 2, 1 - 5, 2 ^ 3
^ Push Partial expression 3, 4 * 2, ( 1 - 5 ) ^ 2 ^ 3
/ Push Partial expression 3, 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
+ Push Partial expression 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
The final output infix expression is: '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'
```
## C
Takes RPN string from command line, string must be enclosed in double quotes. This is necessary since / and ^ are control characters for the command line. The second string, which can be any valid string, is optional and if supplied, the expression tree is printed out as it is built. The final expression is printed out in both cases.
```C
#include
#include
#include
char** components;
int counter = 0;
typedef struct elem{
char data[10];
struct elem* left;
struct elem* right;
}node;
typedef node* tree;
int precedenceCheck(char oper1,char oper2){
return (oper1==oper2)? 0:(oper1=='^')? 1:(oper2=='^')? 2:(oper1=='/')? 1:(oper2=='/')? 2:(oper1=='*')? 1:(oper2=='*')? 2:(oper1=='+')? 1:(oper2=='+')? 2:(oper1=='-')? 1:2;
}
int isOperator(char c){
return (c=='+'||c=='-'||c=='*'||c=='/'||c=='^');
}
void inorder(tree t){
if(t!=NULL){
if(t->left!=NULL && isOperator(t->left->data[0])==1 && (precedenceCheck(t->data[0],t->left->data[0])==1 || (precedenceCheck(t->data[0],t->left->data[0])==0 && t->data[0]=='^'))){
printf("(");
inorder(t->left);
printf(")");
}
else
inorder(t->left);
printf(" %s ",t->data);
if(t->right!=NULL && isOperator(t->right->data[0])==1 && (precedenceCheck(t->data[0],t->right->data[0])==1 || (precedenceCheck(t->data[0],t->right->data[0])==0 && t->data[0]!='^'))){
printf("(");
inorder(t->right);
printf(")");
}
else
inorder(t->right);
}
}
char* getNextString(){
if(counter<0){
printf("\nInvalid RPN !");
exit(0);
}
return components[counter--];
}
tree buildTree(char* obj,char* trace){
tree t = (tree)malloc(sizeof(node));
strcpy(t->data,obj);
t->right = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL;
t->left = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL;
if(trace!=NULL){
printf("\n");
inorder(t);
}
return t;
}
int checkRPN(){
int i, operSum = 0, numberSum = 0;
if(isOperator(components[counter][0])==0)
return 0;
for(i=0;i<=counter;i++)
(isOperator(components[i][0])==1)?operSum++:numberSum++;
return (numberSum - operSum == 1);
}
void buildStack(char* str){
int i;
char* token;
for(i=0;str[i]!=00;i++)
if(str[i]==' ')
counter++;
components = (char**)malloc((counter + 1)*sizeof(char*));
token = strtok(str," ");
i = 0;
while(token!=NULL){
components[i] = (char*)malloc(strlen(token)*sizeof(char));
strcpy(components[i],token);
token = strtok(NULL," ");
i++;
}
}
int main(int argC,char* argV[]){
int i;
tree t;
if(argC==1)
printf("Usage : %s ",argV[0]);
else{
buildStack(argV[1]);
if(checkRPN()==0){
printf("\nInvalid RPN !");
return 0;
}
t = buildTree(getNextString(),argV[2]);
printf("\nFinal infix expression : ");
inorder(t);
}
return 0;
}
```
Output, both final and traced outputs are shown:
```txt
C:\rosettaCode>rpn2Infix.exe "3 4 2 * 1 5 - 2 3 ^ ^ / +"
Final infix expression : 3 + ( 4 * 2 ) / ( 1 - 5 ) ^ 2 ^ 3
C:\rosettaCode>rpn2Infix.exe "1 2 + 3 4 + ^ 5 6 + ^"
Final infix expression : (( 1 + 2 ) ^ ( 3 + 4 )) ^ ( 5 + 6 )
C:\rosettaCode>rpn2Infix.exe "3 4 2 * 1 5 - 2 3 ^ ^ / +" yes
3
2
2 ^ 3
5
1
1 - 5
( 1 - 5 ) ^ 2 ^ 3
2
4
4 * 2
( 4 * 2 ) / ( 1 - 5 ) ^ 2 ^ 3
3
3 + ( 4 * 2 ) / ( 1 - 5 ) ^ 2 ^ 3
Final infix expression : 3 + ( 4 * 2 ) / ( 1 - 5 ) ^ 2 ^ 3
C:\rosettaCode>rpn2Infix.exe "1 2 + 3 4 + ^ 5 6 + ^" yes
6
5
5 + 6
4
3
3 + 4
2
1
1 + 2
( 1 + 2 ) ^ ( 3 + 4 )
(( 1 + 2 ) ^ ( 3 + 4 )) ^ ( 5 + 6 )
Final infix expression : (( 1 + 2 ) ^ ( 3 + 4 )) ^ ( 5 + 6 )
```
## C#
{{trans|Java}}
```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace PostfixToInfix
{
class Program
{
class Operator
{
public Operator(char t, int p, bool i = false)
{
Token = t;
Precedence = p;
IsRightAssociative = i;
}
public char Token { get; private set; }
public int Precedence { get; private set; }
public bool IsRightAssociative { get; private set; }
}
static IReadOnlyDictionary operators = new Dictionary
{
{ '+', new Operator('+', 2) },
{ '-', new Operator('-', 2) },
{ '/', new Operator('/', 3) },
{ '*', new Operator('*', 3) },
{ '^', new Operator('^', 4, true) }
};
class Expression
{
public String ex;
public Operator op;
public Expression(String e)
{
ex = e;
}
public Expression(String e1, String e2, Operator o)
{
ex = String.Format("{0} {1} {2}", e1, o.Token, e2);
op = o;
}
}
static String PostfixToInfix(String postfix)
{
var stack = new Stack();
foreach (var token in Regex.Split(postfix, @"\s+"))
{
char c = token[0];
var op = operators.FirstOrDefault(kv => kv.Key == c).Value;
if (op != null && token.Length == 1)
{
Expression rhs = stack.Pop();
Expression lhs = stack.Pop();
int opPrec = op.Precedence;
int lhsPrec = lhs.op != null ? lhs.op.Precedence : int.MaxValue;
int rhsPrec = rhs.op != null ? rhs.op.Precedence : int.MaxValue;
if ((lhsPrec < opPrec || (lhsPrec == opPrec && c == '^')))
lhs.ex = '(' + lhs.ex + ')';
if ((rhsPrec < opPrec || (rhsPrec == opPrec && c != '^')))
rhs.ex = '(' + rhs.ex + ')';
stack.Push(new Expression(lhs.ex, rhs.ex, op));
}
else
{
stack.Push(new Expression(token));
}
// print intermediate result
Console.WriteLine("{0} -> [{1}]", token,
string.Join(", ", stack.Reverse().Select(e => e.ex)));
}
return stack.Peek().ex;
}
static void Main(string[] args)
{
string[] inputs = { "3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^" };
foreach (var e in inputs)
{
Console.WriteLine("Postfix : {0}", e);
Console.WriteLine("Infix : {0}", PostfixToInfix(e));
Console.WriteLine(); ;
}
Console.ReadLine();
}
}
}
```
```txt
3 -> [3]
4 -> [3, 4]
2 -> [3, 4, 2]
* -> [3, 4 * 2]
1 -> [3, 4 * 2, 1]
5 -> [3, 4 * 2, 1, 5]
- -> [3, 4 * 2, 1 - 5]
2 -> [3, 4 * 2, 1 - 5, 2]
3 -> [3, 4 * 2, 1 - 5, 2, 3]
^ -> [3, 4 * 2, 1 - 5, 2 ^ 3]
^ -> [3, 4 * 2, (1 - 5) ^ 2 ^ 3]
/ -> [3, 4 * 2 / (1 - 5) ^ 2 ^ 3]
+ -> [3 + 4 * 2 / (1 - 5) ^ 2 ^ 3]
Infix : 3 + 4 * 2 / (1 - 5) ^ 2 ^ 3
Postfix : 1 2 + 3 4 + ^ 5 6 + ^
1 -> [1]
2 -> [1, 2]
+ -> [1 + 2]
3 -> [1 + 2, 3]
4 -> [1 + 2, 3, 4]
+ -> [1 + 2, 3 + 4]
^ -> [(1 + 2) ^ (3 + 4)]
5 -> [(1 + 2) ^ (3 + 4), 5]
6 -> [(1 + 2) ^ (3 + 4), 5, 6]
+ -> [(1 + 2) ^ (3 + 4), 5 + 6]
^ -> [((1 + 2) ^ (3 + 4)) ^ (5 + 6)]
Infix : ((1 + 2) ^ (3 + 4)) ^ (5 + 6)
```
## C++
Very primitive implementation, doesn't use any parsing libraries which would shorten this greatly.
```Cpp
#include
#include
#include
#include
## Nim
{{trans|Go}}
```nim
import tables, strutils
const nPrec = 9
let ops: Table[string, tuple[prec: int, rAssoc: bool]] =
{ "^": (4, true)
, "*": (3, false)
, "/": (3, false)
, "+": (2, false)
, "-": (2, false)
}.toTable
proc parseRPN(e: string) =
echo "postfix: ", e
var stack = newSeq[tuple[prec: int, expr: string]]()
for tok in e.split:
echo "Token: ", tok
if ops.hasKey tok:
let op = ops[tok]
let rhs = stack.pop
var lhs = stack.pop
if lhs.prec < op.prec or (lhs.prec == op.prec and op.rAssoc):
lhs.expr = "(" & lhs.expr & ")"
lhs.expr.add " " & tok & " "
if rhs.prec < op.prec or (rhs.prec == op.prec and not op.rAssoc):
lhs.expr.add "(" & rhs.expr & ")"
else:
lhs.expr.add rhs.expr
lhs.prec = op.prec
stack.add lhs
else:
stack.add((nPrec, tok))
for f in stack:
echo " ", f.prec, " ", f.expr
echo "infix: ", stack[0].expr
for test in ["3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^"]:
test.parseRPN
```
Output:
```txt
postfix: 3 4 2 * 1 5 - 2 3 ^ ^ / +
Token: 3
9 3
Token: 4
9 3
9 4
Token: 2
9 3
9 4
9 2
Token: *
9 3
3 4 * 2
Token: 1
9 3
3 4 * 2
9 1
Token: 5
9 3
3 4 * 2
9 1
9 5
Token: -
9 3
3 4 * 2
2 1 - 5
Token: 2
9 3
3 4 * 2
2 1 - 5
9 2
Token: 3
9 3
3 4 * 2
2 1 - 5
9 2
9 3
Token: ^
9 3
3 4 * 2
2 1 - 5
4 2 ^ 3
Token: ^
9 3
3 4 * 2
4 (1 - 5) ^ 2 ^ 3
Token: /
9 3
3 4 * 2 / (1 - 5) ^ 2 ^ 3
Token: +
2 3 + 4 * 2 / (1 - 5) ^ 2 ^ 3
infix: 3 + 4 * 2 / (1 - 5) ^ 2 ^ 3
postfix: 1 2 + 3 4 + ^ 5 6 + ^
Token: 1
9 1
Token: 2
9 1
9 2
Token: +
2 1 + 2
Token: 3
2 1 + 2
9 3
Token: 4
2 1 + 2
9 3
9 4
Token: +
2 1 + 2
2 3 + 4
Token: ^
4 (1 + 2) ^ (3 + 4)
Token: 5
4 (1 + 2) ^ (3 + 4)
9 5
Token: 6
4 (1 + 2) ^ (3 + 4)
9 5
9 6
Token: +
4 (1 + 2) ^ (3 + 4)
2 5 + 6
Token: ^
4 ((1 + 2) ^ (3 + 4)) ^ (5 + 6)
infix: ((1 + 2) ^ (3 + 4)) ^ (5 + 6)
```
## Perl
```perl
use strict;
use warnings;
use feature 'say';
my $number = '[+-/$]?(?:\.\d+|\d+(?:\.\d*)?)';
my $operator = '[-+*/^]';
my @tests = ('1 2 + 3 4 + ^ 5 6 + ^', '3 4 2 * 1 5 - 2 3 ^ ^ / +');
for (@tests) {
my(@elems,$n);
$n = -1;
while (
s/
\s* (?$number) # 1st operand (will be 'left' in infix)
\s+ (?$number) # 2nd operand (will be 'right' in infix)
\s+ (?$operator) # operator
(?:\s+|$) # more to parse, or done?
/
' '.('$'.++$n).' ' # placeholders
/ex) {
$elems[$n] = "($+{left}$+{op}$+{right})" # infix expression
}
while (
s/ (\$)(\d+) # for each placeholder
/ $elems[$2] # evaluate expression, substitute numeric value
/ex
) { say } # track progress
say '=>' . substr($_,2,-2)."\n";
}
```
{{out}}
```txt
($2^$3)
(($0^$1)^$3)
(((1+2)^$1)^$3)
(((1+2)^(3+4))^$3)
(((1+2)^(3+4))^(5+6))
=>((1+2)^(3+4))^(5+6)
(3+$4)
(3+($0/$3))
(3+((4*2)/$3))
(3+((4*2)/($1^$2)))
(3+((4*2)/((1-5)^$2)))
(3+((4*2)/((1-5)^(2^3))))
=>3+((4*2)/((1-5)^(2^3)))
```
## Perl 6
```perl6
my @tests = '3 4 2 * 1 5 - 2 3 ^ ^ / +',
'1 2 + 3 4 + ^ 5 6 + ^';
say rpm-to-infix($_) for @tests;
sub p ($pair, $prec) {
$pair.key < $prec ?? "( $pair.value() )" !! $pair.value
}
sub rpm-to-infix($string) {
say "
### ===========
\n$string";
my @stack;
for $string.words {
when /\d/ { @stack.push: 9 => $_ }
my $y = @stack.pop;
my $x = @stack.pop;
when '^' { @stack.push: 4 => ~(p($x,5), $_, p($y,4)) }
when '*' | '/' { @stack.push: 3 => ~(p($x,3), $_, p($y,3)) }
when '+' | '-' { @stack.push: 2 => ~(p($x,2), $_, p($y,2)) }
# LEAVE { say @stack } # phaser not yet implemented in this context
}
say "-----------------";
@stack».value;
}
```
{{out}}
```txt
### ===========
3 4 2 * 1 5 - 2 3 ^ ^ / +
-----------------
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
### ===========
1 2 + 3 4 + ^ 5 6 + ^
-----------------
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
```
## Phix
```Phix
integer show_workings = 1
constant operators = {"^","*","/","+","-"},
precedence = { 4, 3, 3, 2, 2 },
rassoc = {'r', 0 ,'l', 0 ,'l'}
procedure parseRPN(string expr, string expected)
sequence stack = {}
sequence ops = split(expr)
string lhs, rhs
integer lprec,rprec
printf(1,"Postfix input: %-30s%s", {expr,iff(show_workings?'\n':'\t')})
if length(ops)=0 then ?"error" return end if
for i=1 to length(ops) do
string op = ops[i]
integer k = find(op,operators)
if k=0 then
stack = append(stack,{9,op})
else
if length(stack)<2 then ?"error" return end if
{rprec,rhs} = stack[$]; stack = stack[1..$-1]
{lprec,lhs} = stack[$]
integer prec = precedence[k]
integer assoc = rassoc[k]
if lprec "3 + 4 * 2 / (1 - 5) \^ 2 \^ 3"
: (rpnToInfix "1 2 + 3 4 + \^ 5 6 + \^")
Token Stack
1 ((9 . 1))
2 ((9 . 2) (9 . 1))
+ ((2 . "1 + 2"))
3 ((9 . 3) (2 . "1 + 2"))
4 ((9 . 4) (9 . 3) (2 . "1 + 2"))
+ ((2 . "3 + 4") (2 . "1 + 2"))
^ ((4 . "(1 + 2) \^ (3 + 4)"))
5 ((9 . 5) (4 . "(1 + 2) \^ (3 + 4)"))
6 ((9 . 6) (9 . 5) (4 . "(1 + 2) \^ (3 + 4)"))
+ ((2 . "5 + 6") (4 . "(1 + 2) \^ (3 + 4)"))
^ ((4 . "((1 + 2) \^ (3 + 4)) \^ (5 + 6)"))
-> "((1 + 2) \^ (3 + 4)) \^ (5 + 6)"
```
## PL/I
```PL/I
/* Uses a push-down pop-up stack for the stack (instead of array) */
cvt: procedure options (main); /* 10 Sept. 2012 */
declare (true initial ('1'b), false initial ('0'b) ) bit (1);
declare list character (1) controlled, written bit (1) controlled;
declare (RPN, out) character (100) varying;
declare s character (1);
declare input_priority (5) fixed (1) static initial (1, 1, 2, 2, 3);
declare stack_priority (5) fixed (1) static initial (1, 1, 2, 2, 4);
declare (i, ki, kl) fixed binary;
put ('Convert a Reverse Polish expression to orthodox.');
put skip list ('Enclose the expression in apostrophes:');
get list (RPN);
put skip list ('The original Reverse Polish expression = ' || RPN);
out = '';
allocate list, written;
list = substr(RPN, length(RPN), 1); written = false;
translation:
do i = length (RPN)-1 to 1 by -1;
s = substr(RPN, i, 1);
if s = ' ' then iterate;
ki = index('+-*/^', s);
kl = index('+-*/^', list);
if ki > 0 then /* we have an operator */
do;
if input_priority (ki) < stack_priority (kl) then
do; /* transfer ')' to list, then operator. */
allocate list, written;
list = '('; written = false;
out = ')' || out;
end;
allocate list, written;
list = s; written = false;
end;
else /* It's a variable name */
do;
out = s || out;
next_list:
if allocation(list) > 0 then if written then free written, list;
if allocation(list) > 0 then if list = '(' then
do; out = list || out; free written, list; end;
if allocation (list) = 0 then leave translation;
if written then go to next_list;
written = true;
out = list || out; /* Output an operator. */
end;
put skip edit ('INPUT=' || s) (a); call show_stack;
put edit (' OUTPUT=', out) (col(30), 2 a);
end;
put skip list ('ALGEBRAIC EXPRESSION=', out);
end cvt;
```
Outputs:
```txt
The original Reverse Polish expression = 3 4 2 * 1 5 - 2 3 ^ ^ / +
INPUT=/ STACK=/+ OUTPUT=
INPUT=^ STACK=^/+ OUTPUT=
INPUT=^ STACK=^(^/+ OUTPUT=)
INPUT=3 STACK=^(^/+ OUTPUT=^3)
INPUT=2 STACK=^/+ OUTPUT=^(2^3)
INPUT=- STACK=-(^/+ OUTPUT=)^(2^3)
INPUT=5 STACK=-(^/+ OUTPUT=-5)^(2^3)
INPUT=1 STACK=/+ OUTPUT=/(1-5)^(2^3)
INPUT=* STACK=*/+ OUTPUT=/(1-5)^(2^3)
INPUT=2 STACK=*/+ OUTPUT=*2/(1-5)^(2^3)
INPUT=4 STACK=+ OUTPUT=+4*2/(1-5)^(2^3)
ALGEBRAIC EXPRESSION= 3+4*2/(1-5)^(2^3)
The original Reverse Polish expression = 1 2+ 3 4 + ^ 5 6 + ^
INPUT=+ STACK=+(^ OUTPUT=)
INPUT=6 STACK=+(^ OUTPUT=+6)
INPUT=5 STACK=^ OUTPUT=^(5+6)
INPUT=^ STACK=^(^ OUTPUT=)^(5+6)
INPUT=+ STACK=+(^(^ OUTPUT=))^(5+6)
INPUT=4 STACK=+(^(^ OUTPUT=+4))^(5+6)
INPUT=3 STACK=^(^ OUTPUT=^(3+4))^(5+6)
INPUT=+ STACK=+(^(^ OUTPUT=)^(3+4))^(5+6)
INPUT=2 STACK=+(^(^ OUTPUT=+2)^(3+4))^(5+6)
ALGEBRAIC EXPRESSION= ((1+2)^(3+4))^(5+6)
```
Procedure to display stack:
```txt
show_stack: procedure;
declare stack character (1) controlled;
put edit (' STACK=') (a);
do while (allocation (list) > 0);
allocate stack; stack = list; free list; put edit (stack) (a);
end;
do while (allocation (stack) > 0);
allocate list; list = stack; free stack;
end;
end show_stack;
```
## Python
```python
"""
>>> # EXAMPLE USAGE
>>> result = rpn_to_infix('3 4 2 * 1 5 - 2 3 ^ ^ / +', VERBOSE=True)
TOKEN STACK
3 ['3']
4 ['3', '4']
2 ['3', '4', '2']
* ['3', Node('2','*','4')]
1 ['3', Node('2','*','4'), '1']
5 ['3', Node('2','*','4'), '1', '5']
- ['3', Node('2','*','4'), Node('5','-','1')]
2 ['3', Node('2','*','4'), Node('5','-','1'), '2']
3 ['3', Node('2','*','4'), Node('5','-','1'), '2', '3']
^ ['3', Node('2','*','4'), Node('5','-','1'), Node('3','^','2')]
^ ['3', Node('2','*','4'), Node(Node('3','^','2'),'^',Node('5','-','1'))]
/ ['3', Node(Node(Node('3','^','2'),'^',Node('5','-','1')),'/',Node('2','*','4'))]
+ [Node(Node(Node(Node('3','^','2'),'^',Node('5','-','1')),'/',Node('2','*','4')),'+','3')]
"""
prec_dict = {'^':4, '*':3, '/':3, '+':2, '-':2}
assoc_dict = {'^':1, '*':0, '/':0, '+':0, '-':0}
class Node:
def __init__(self,x,op,y=None):
self.precedence = prec_dict[op]
self.assocright = assoc_dict[op]
self.op = op
self.x,self.y = x,y
def __str__(self):
"""
Building an infix string that evaluates correctly is easy.
Building an infix string that looks pretty and evaluates
correctly requires more effort.
"""
# easy case, Node is unary
if self.y == None:
return '%s(%s)'%(self.op,str(self.x))
# determine left side string
str_y = str(self.y)
if self.y < self or \
(self.y == self and self.assocright) or \
(str_y[0] is '-' and self.assocright):
str_y = '(%s)'%str_y
# determine right side string and operator
str_x = str(self.x)
str_op = self.op
if self.op is '+' and not isinstance(self.x, Node) and str_x[0] is '-':
str_x = str_x[1:]
str_op = '-'
elif self.op is '-' and not isinstance(self.x, Node) and str_x[0] is '-':
str_x = str_x[1:]
str_op = '+'
elif self.x < self or \
(self.x == self and not self.assocright and \
getattr(self.x, 'op', 1) != getattr(self, 'op', 2)):
str_x = '(%s)'%str_x
return ' '.join([str_y, str_op, str_x])
def __repr__(self):
"""
>>> repr(Node('3','+','4')) == repr(eval(repr(Node('3','+','4'))))
True
"""
return 'Node(%s,%s,%s)'%(repr(self.x), repr(self.op), repr(self.y))
def __lt__(self, other):
if isinstance(other, Node):
return self.precedence < other.precedence
return self.precedence < prec_dict.get(other,9)
def __gt__(self, other):
if isinstance(other, Node):
return self.precedence > other.precedence
return self.precedence > prec_dict.get(other,9)
def __eq__(self, other):
if isinstance(other, Node):
return self.precedence == other.precedence
return self.precedence > prec_dict.get(other,9)
def rpn_to_infix(s, VERBOSE=False):
"""
converts rpn notation to infix notation for string s
"""
if VERBOSE : print('TOKEN STACK')
stack=[]
for token in s.replace('^','^').split():
if token in prec_dict:
stack.append(Node(stack.pop(),token,stack.pop()))
else:
stack.append(token)
# can't use \t in order to make global docstring pass doctest
if VERBOSE : print(token+' '*(7-len(token))+repr(stack))
return str(stack[0])
strTest = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
strResult = rpn_to_infix(strTest, VERBOSE=False)
print ("Input: ",strTest)
print ("Output:",strResult)
print()
strTest = "1 2 + 3 4 + ^ 5 6 + ^"
strResult = rpn_to_infix(strTest, VERBOSE=False)
print ("Input: ",strTest)
print ("Output:",strResult)
```
Output:
```txt
Input: 3 4 2 * 1 5 - 2 3 ^ ^ / +
Output: 3 + 4 * 2 / (1 - 5) ^ 2 ^ 3
Input: 1 2 + 3 4 + ^ 5 6 + ^
Output: ((1 + 2) ^ (3 + 4)) ^ (5 + 6)
```
## Racket
{{trans|AWK}}
```racket
#lang racket
(require racket/dict)
(define (RPN->infix expr)
(define-values (res _)
(for/fold ([stack '()] [prec '()]) ([t expr])
(show t stack prec)
(cond
[(dict-has-key? operators t)
(match-define (list pt at) (dict-ref operators t))
(match-define (list y x ss ...) stack)
(match-define (list py px ps ...) prec)
(define fexpr
(cond
[(> pt (max px py)) "(~a) ~a (~a)"]
[(or (< px pt) (and (= pt px) (eq? at 'r))) "(~a) ~a ~a"]
[(or (< py pt) (and (= pt py) (eq? at 'l))) "~a ~a (~a)"]
[else "~a ~a ~a"]))
(define term (format fexpr x t y))
(values (cons term ss) (cons pt ps))]
[else (values (cons t stack) (cons +inf.0 prec))])))
(car res))
;; the list of operators and their properties
(define operators '((+ 2 l) (- 2 l) (* 3 l) (/ 3 l) (^ 4 r)))
;; printing out the intermediate stages
(define (show t stack prec)
(printf "~a\t" t)
(for ([s stack] [p prec])
(if (eq? +inf.0 p) (printf "[~a] " s) (printf "[~a {~a}] " s p)))
(newline))
```
Output:
```txt
-> (RPN->infix '(3 4 2 * 1 5 - 2 3 ^ ^ / +))
3
4 [3]
2 [4] [3]
* [2] [4] [3]
1 [4 * 2 {3}] [3]
5 [1] [4 * 2 {3}] [3]
- [5] [1] [4 * 2 {3}] [3]
2 [1 - 5 {2}] [4 * 2 {3}] [3]
3 [2] [1 - 5 {2}] [4 * 2 {3}] [3]
^ [3] [2] [1 - 5 {2}] [4 * 2 {3}] [3]
^ [2 ^ 3 {4}] [1 - 5 {2}] [4 * 2 {3}] [3]
/ [(1 - 5) ^ 2 ^ 3 {4}] [4 * 2 {3}] [3]
+ [4 * 2 / (1 - 5) ^ 2 ^ 3 {3}] [3]
"3 + 4 * 2 / (1 - 5) ^ 2 ^ 3"
-> (RPN->infix '(1 2 + 3 4 + ^))
1
2 [1]
+ [2] [1]
3 [1 + 2 {2}]
4 [3] [1 + 2 {2}]
+ [4] [3] [1 + 2 {2}]
^ [3 + 4 {2}] [1 + 2 {2}]
"(1 + 2) ^ (3 + 4)"
-> (RPN->infix '(moon stars mud + * fire soup * ^))
moon
stars [moon]
mud [stars] [moon]
+ [mud] [stars] [moon]
* [stars + mud {2}] [moon]
fire [moon * (stars + mud) {3}]
soup [fire] [moon * (stars + mud) {3}]
* [soup] [fire] [moon * (stars + mud) {3}]
^ [fire * soup {3}] [moon * (stars + mud) {3}]
"(moon * (stars + mud)) ^ (fire * soup)"
```
## REXX
{{trans|AWK}}
{{trans|Tcl}}
A Yen symbol '''¥''' was used instead of a '''9''' to make it apparenet that it's just a placeholder.
The same reasoning was used for the ''operator associations'' (the left ◄ and right ► arrow symbols).
```rexx
/*REXX program converts Reverse Polish Notation (RPN) ──► infix notation*/
showAction = 1 /* 0 if no showActions wanted. */
# = 0 /*initialize stack pointer to 0. */
oS = '+ - / * ^' /*operator symbols. */
oP = '2 2 3 3 4' /*operator priorities. */
oA = '◄ ◄ ◄ ◄ ►' /*operator associations. */
say "infix: " toInfix( "3 4 2 * 1 5 - 2 3 ^ ^ / +" )
say "infix: " toInfix( "1 2 + 3 4 + ^ 5 6 + ^" ) /* [↓] Deutsch.*/
say "infix: " toInfix( "Mond Sterne Schlamm + * Feur Suppe * ^" )
exit /*stick a fork in it, we're 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); ?=word(RPN,N) /*process each of the RPN tokens.*/
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
───────────────────────────────────────────────────────────────────────────────
RPN: 3 4 2 * 1 5 - 2 3 ^ ^ / +
3 ──► {¥ 3}
4 ──► {¥ 3} {¥ 4}
2 ──► {¥ 3} {¥ 4} {¥ 2}
* ──► {¥ 3} {3 4 * 2}
1 ──► {¥ 3} {3 4 * 2} {¥ 1}
5 ──► {¥ 3} {3 4 * 2} {¥ 1} {¥ 5}
- ──► {¥ 3} {3 4 * 2} {2 1 - 5}
2 ──► {¥ 3} {3 4 * 2} {2 1 - 5} {¥ 2}
3 ──► {¥ 3} {3 4 * 2} {2 1 - 5} {¥ 2} {¥ 3}
^ ──► {¥ 3} {3 4 * 2} {2 1 - 5} {4 2 ^ 3}
^ ──► {¥ 3} {3 4 * 2} {4 ( 1 - 5) ^ 2 ^ 3}
/ ──► {¥ 3} {3 4 * 2 / ( 1 - 5) ^ 2 ^ 3}
+ ──► {2 3 + 4 * 2 / ( 1 - 5) ^ 2 ^ 3}
infix: 3 + 4 * 2 / ( 1 - 5) ^ 2 ^ 3
───────────────────────────────────────────────────────────────────────────────
RPN: 1 2 + 3 4 + ^ 5 6 + ^
1 ──► {¥ 1}
2 ──► {¥ 1} {¥ 2}
+ ──► {2 1 + 2}
3 ──► {2 1 + 2} {¥ 3}
4 ──► {2 1 + 2} {¥ 3} {¥ 4}
+ ──► {2 1 + 2} {2 3 + 4}
^ ──► {4 ( 1 + 2) ^ ( 3 + 4)}
5 ──► {4 ( 1 + 2) ^ ( 3 + 4)} {¥ 5}
6 ──► {4 ( 1 + 2) ^ ( 3 + 4)} {¥ 5} {¥ 6}
+ ──► {4 ( 1 + 2) ^ ( 3 + 4)} {2 5 + 6}
^ ──► {4 (( 1 + 2) ^ ( 3 + 4)) ^ ( 5 + 6)}
infix: (( 1 + 2) ^ ( 3 + 4)) ^ ( 5 + 6)
───────────────────────────────────────────────────────────────────────────────
RPN: Mond Sterne Schlamm + * Feur Suppe * ^
Mond ──► {¥ Mond}
Sterne ──► {¥ Mond} {¥ Sterne}
Schlamm ──► {¥ Mond} {¥ Sterne} {¥ Schlamm}
+ ──► {¥ Mond} {2 Sterne + Schlamm}
* ──► {3 Mond * ( Sterne + Schlamm)}
Feur ──► {3 Mond * ( Sterne + Schlamm)} {¥ Feur}
Suppe ──► {3 Mond * ( Sterne + Schlamm)} {¥ Feur} {¥ Suppe}
* ──► {3 Mond * ( Sterne + Schlamm)} {3 Feur * Suppe}
^ ──► {4 ( Mond * ( Sterne + Schlamm)) ^ ( Feur * Suppe)
}
infix: ( Mond * ( Sterne + Schlamm)) ^ ( Feur * Suppe)
```
## Ruby
{{incorrect|Ruby|Fails with right-associativity of exponentiation. RPNExpression.new("5 6 ^ 7 ^").to_infix
wrongly returns "5 ^ 6 ^ 7". Correct answer is "(5 ^ 6) ^ 7".}}
See [[Parsing/RPN/Ruby]]
```ruby
rpn = RPNExpression.new("3 4 2 * 1 5 - 2 3 ^ ^ / +")
infix = rpn.to_infix
ruby = rpn.to_ruby
```
outputs
```txt
for RPN expression: 3 4 2 * 1 5 - 2 3 ^ ^ / +
Term Action Stack
3 PUSH [node[3]]
4 PUSH [node[3], node[4]]
2 PUSH [node[3], node[4], node[2]]
* MUL [node[3], node[*]]
1 PUSH [node[3], node[*], node[1]]
5 PUSH [node[3], node[*], node[1], node[5]]
- SUB [node[3], node[*], node[-]]
2 PUSH [node[3], node[*], node[-], node[2]]
3 PUSH [node[3], node[*], node[-], node[2], node[3]]
^ EXP [node[3], node[*], node[-], node[^]]
^ EXP [node[3], node[*], node[^], right=node[^]>]
/ DIV [node[3], node[/], right=node[^], right=node[^]>>]
+ ADD [node[+], right=node[^], right=node[^]>>>]
Infix = 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
Ruby = 3 + 4 * 2.to_f / ( 1 - 5 ) ** 2 ** 3
```
## Sidef
{{trans|Perl 6}}
```ruby
func p(pair, prec) {
pair[0] < prec ? "( #{pair[1]} )" : pair[1]
}
func rpm_to_infix(string) {
say "#{'='*17}\n#{string}"
var stack = []
string.each_word { |w|
if (w ~~ /\d/) {
stack << [9, Num(w)]
}
else {
var y = stack.pop
var x = stack.pop
given(w) {
when ('^') { stack << [4, [p(x,5), w, p(y,4)].join(' ')] }
when (<* />) { stack << [3, [p(x,3), w, p(y,3)].join(' ')] }
when (<+ ->) { stack << [2, [p(x,2), w, p(y,2)].join(' ')] }
}
say stack
}
}
say '-'*17
stack.map{_[1]}
}
var tests = [
'3 4 2 * 1 5 - 2 3 ^ ^ / +',
'1 2 + 3 4 + ^ 5 6 + ^',
]
tests.each { say rpm_to_infix(_).join(' ') }
```
{{out}}
```txt
### ===========
3 4 2 * 1 5 - 2 3 ^ ^ / +
[[9, 3], [3, "4 * 2"]]
[[9, 3], [3, "4 * 2"], [2, "1 - 5"]]
[[9, 3], [3, "4 * 2"], [2, "1 - 5"], [4, "2 ^ 3"]]
[[9, 3], [3, "4 * 2"], [4, "( 1 - 5 ) ^ 2 ^ 3"]]
[[9, 3], [3, "4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"]]
[[2, "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"]]
-----------------
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
### ===========
1 2 + 3 4 + ^ 5 6 + ^
[[2, "1 + 2"]]
[[2, "1 + 2"], [2, "3 + 4"]]
[[4, "( 1 + 2 ) ^ ( 3 + 4 )"]]
[[4, "( 1 + 2 ) ^ ( 3 + 4 )"], [2, "5 + 6"]]
[[4, "( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )"]]
-----------------
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
```
## Tcl
```tcl
package require Tcl 8.5
# Helpers
proc precassoc op {
dict get {^ {4 right} * {3 left} / {3 left} + {2 left} - {2 left}} $op
}
proc pop stk {
upvar 1 $stk s
set val [lindex $s end]
set s [lreplace $s end end]
return $val
}
proc rpn2infix rpn {
foreach token $rpn {
switch $token {
"^" - "/" - "*" - "+" - "-" {
lassign [pop stack] bprec b
lassign [pop stack] aprec a
lassign [precassoc $token] p assoc
if {$aprec < $p || ($aprec == $p && $assoc eq "right")} {
set a "($a)"
}
if {$bprec < $p || ($bprec == $p && $assoc eq "left")} {
set b "($b)"
}
lappend stack [list $p "$a $token $b"]
}
default {
lappend stack [list 9 $token]
}
}
puts "$token -> $stack"
}
return [lindex $stack end 1]
}
puts [rpn2infix {3 4 2 * 1 5 - 2 3 ^ ^ / +}]
puts [rpn2infix {1 2 + 3 4 + ^ 5 6 + ^}]
```
Output:
```txt
3 -> {9 3}
4 -> {9 3} {9 4}
2 -> {9 3} {9 4} {9 2}
* -> {9 3} {3 {4 * 2}}
1 -> {9 3} {3 {4 * 2}} {9 1}
5 -> {9 3} {3 {4 * 2}} {9 1} {9 5}
- -> {9 3} {3 {4 * 2}} {2 {1 - 5}}
2 -> {9 3} {3 {4 * 2}} {2 {1 - 5}} {9 2}
3 -> {9 3} {3 {4 * 2}} {2 {1 - 5}} {9 2} {9 3}
^ -> {9 3} {3 {4 * 2}} {2 {1 - 5}} {4 {2 ^ 3}}
^ -> {9 3} {3 {4 * 2}} {4 {(1 - 5) ^ 2 ^ 3}}
/ -> {9 3} {3 {4 * 2 / (1 - 5) ^ 2 ^ 3}}
+ -> {2 {3 + 4 * 2 / (1 - 5) ^ 2 ^ 3}}
3 + 4 * 2 / (1 - 5) ^ 2 ^ 3
1 -> {9 1}
2 -> {9 1} {9 2}
+ -> {2 {1 + 2}}
3 -> {2 {1 + 2}} {9 3}
4 -> {2 {1 + 2}} {9 3} {9 4}
+ -> {2 {1 + 2}} {2 {3 + 4}}
^ -> {4 {(1 + 2) ^ (3 + 4)}}
5 -> {4 {(1 + 2) ^ (3 + 4)}} {9 5}
6 -> {4 {(1 + 2) ^ (3 + 4)}} {9 5} {9 6}
+ -> {4 {(1 + 2) ^ (3 + 4)}} {2 {5 + 6}}
^ -> {4 {((1 + 2) ^ (3 + 4)) ^ (5 + 6)}}
((1 + 2) ^ (3 + 4)) ^ (5 + 6)
```
## TXR
This solution is a little long because it works by translating RPN to fully parenthesized prefix (Lisp notation).
Also, it improves upon the problem slightly. Note that for the operators *
and +
, the associativity is configured asnil
("no associativity") rather than left-to-right. This is because these operators obey the associative property: (a + b) + c
is a + (b + c)
, and so we usually write a + b + c or a * b * c
without any parentheses, leaving it ambiguous which addition is done first. Associativity is not important for these operators.
The lisp-to-infix
filter then takes advantage of this non-associativity in minimizing the parentheses.
```txrlisp
;; alias for circumflex, which is reserved syntax
(defvar exp (intern "^"))
(defvar *prec* ^((,exp . 4) (* . 3) (/ . 3) (+ . 2) (- . 2)))
(defvar *asso* ^((,exp . :right) (* . nil)
(/ . :left) (+ . nil) (- . :left)))
(defun debug-print (label val)
(format t "~a: ~a\n" label val)
val)
(defun rpn-to-lisp (rpn)
(let (stack)
(each ((term rpn))
(if (symbolp (debug-print "rpn term" term))
(let ((right (pop stack))
(left (pop stack)))
(push ^(,term ,left ,right) stack))
(push term stack))
(debug-print "stack" stack))
(if (rest stack)
(return-from error "*excess stack elements*"))
(debug-print "lisp" (pop stack))))
(defun prec (term)
(or (cdr (assoc term *prec*)) 99))
(defun asso (term dfl)
(or (cdr (assoc term *asso*)) dfl))
(defun inf-term (op term left-or-right)
(if (atom term)
`@term`
(let ((pt (prec (car term)))
(po (prec op))
(at (asso (car term) left-or-right))
(ao (asso op left-or-right)))
(cond
((< pt po) `(@(lisp-to-infix term))`)
((> pt po) `@(lisp-to-infix term)`)
((and (eq at ao) (eq left-or-right ao)) `@(lisp-to-infix term)`)
(t `(@(lisp-to-infix term))`)))))
(defun lisp-to-infix (lisp)
(tree-case lisp
((op left right) (let ((left-inf (inf-term op left :left))
(right-inf (inf-term op right :right)))
`@{left-inf} @op @{right-inf}`))
(() (return-from error "*stack underflow*"))
(else `@lisp`)))
(defun string-to-rpn (str)
(debug-print "rpn"
(mapcar (do if (int-str @1) (int-str @1) (intern @1))
(tok-str str #/[^ \t]+/))))
(debug-print "infix"
(block error
(tree-case *args*
((a b . c) "*excess args*")
((a) (lisp-to-infix (rpn-to-lisp (string-to-rpn a))))
(else "*arg needed*"))))
```
{{out}}
```txt
$ txr rpn.tl '3 4 2 * 1 5 - 2 3 ^ ^ / +'
rpn: (3 4 2 * 1 5 - 2 3 ^ ^ / +)
rpn term: 3
stack: (3)
rpn term: 4
stack: (4 3)
rpn term: 2
stack: (2 4 3)
rpn term: *
stack: ((* 4 2) 3)
rpn term: 1
stack: (1 (* 4 2) 3)
rpn term: 5
stack: (5 1 (* 4 2) 3)
rpn term: -
stack: ((- 1 5) (* 4 2) 3)
rpn term: 2
stack: (2 (- 1 5) (* 4 2) 3)
rpn term: 3
stack: (3 2 (- 1 5) (* 4 2) 3)
rpn term: ^
stack: ((^ 2 3) (- 1 5) (* 4 2) 3)
rpn term: ^
stack: ((^ (- 1 5) (^ 2 3)) (* 4 2) 3)
rpn term: /
stack: ((/ (* 4 2) (^ (- 1 5) (^ 2 3))) 3)
rpn term: +
stack: ((+ 3 (/ (* 4 2) (^ (- 1 5) (^ 2 3)))))
lisp: (+ 3 (/ (* 4 2) (^ (- 1 5) (^ 2 3))))
infix: 3 + 4 * 2 / (1 - 5) ^ 2 ^ 3
$ txr rpn.tl '1 2 + 3 4 + ^ 5 6 + ^'
rpn: (1 2 + 3 4 + ^ 5 6 + ^)
rpn term: 1
stack: (1)
rpn term: 2
stack: (2 1)
rpn term: +
stack: ((+ 1 2))
rpn term: 3
stack: (3 (+ 1 2))
rpn term: 4
stack: (4 3 (+ 1 2))
rpn term: +
stack: ((+ 3 4) (+ 1 2))
rpn term: ^
stack: ((^ (+ 1 2) (+ 3 4)))
rpn term: 5
stack: (5 (^ (+ 1 2) (+ 3 4)))
rpn term: 6
stack: (6 5 (^ (+ 1 2) (+ 3 4)))
rpn term: +
stack: ((+ 5 6) (^ (+ 1 2) (+ 3 4)))
rpn term: ^
stack: ((^ (^ (+ 1 2) (+ 3 4)) (+ 5 6)))
lisp: (^ (^ (+ 1 2) (+ 3 4)) (+ 5 6))
infix: ((1 + 2) ^ (3 + 4)) ^ (5 + 6)
```
Associativity tests (abbreviated output):
```txt
$ txr rpn.tl '1 2 3 + +'
[ ... ]
infix: 1 + 2 + 3
$ txr rpn.tl '1 2 + 3 +'
[ ... ]
infix: 1 + 2 + 3
$ txr rpn.tl '1 2 3 ^ ^'
rpn tokens: [1 2 3 ^ ^]
[ ... ]
infix: 1 ^ 2 ^ 3
$ txr rpn.tl '1 2 ^ 3 ^'
[ ... ]
infix: (1 ^ 2) ^ 3
$ txr rpn.tl '1 1 - 3 +'
[ .. ]
infix: 1 - 1 + 3
$ txr rpn.tl '3 1 1 - +'
[ .. ]
infix: 3 + (1 - 1)
```
## Visual Basic .NET
{{trans|C#}}
```vbnet
Option Strict On
Imports System.Text.RegularExpressions
Module Module1
Class Operator_
Sub New(t As Char, p As Integer, Optional i As Boolean = False)
Token = t
Precedence = p
IsRightAssociative = i
End Sub
Property Token As Char
Get
Return m_token
End Get
Private Set(value As Char)
m_token = value
End Set
End Property
Property Precedence As Integer
Get
Return m_precedence
End Get
Private Set(value As Integer)
m_precedence = value
End Set
End Property
Property IsRightAssociative As Boolean
Get
Return m_right
End Get
Private Set(value As Boolean)
m_right = value
End Set
End Property
Private m_token As Char
Private m_precedence As Integer
Private m_right As Boolean
End Class
ReadOnly operators As New Dictionary(Of Char, Operator_) From {
{"+"c, New Operator_("+"c, 2)},
{"-"c, New Operator_("-"c, 2)},
{"/"c, New Operator_("/"c, 3)},
{"*"c, New Operator_("*"c, 3)},
{"^"c, New Operator_("^"c, 4, True)}
}
Class Expression
Public Sub New(e As String)
Ex = e
End Sub
Sub New(e1 As String, e2 As String, o As Operator_)
Ex = String.Format("{0} {1} {2}", e1, o.Token, e2)
Op = o
End Sub
ReadOnly Property Ex As String
ReadOnly Property Op As Operator_
End Class
Function PostfixToInfix(postfix As String) As String
Dim stack As New Stack(Of Expression)
For Each token As String In Regex.Split(postfix, "\s+")
Dim c = token(0)
Dim op = operators.FirstOrDefault(Function(kv) kv.Key = c).Value
If Not IsNothing(op) AndAlso token.Length = 1 Then
Dim rhs = stack.Pop()
Dim lhs = stack.Pop()
Dim opPrec = op.Precedence
Dim lhsPrec = If(IsNothing(lhs.Op), Integer.MaxValue, lhs.Op.Precedence)
Dim rhsPrec = If(IsNothing(rhs.Op), Integer.MaxValue, rhs.Op.Precedence)
Dim newLhs As String
If lhsPrec < opPrec OrElse (lhsPrec = opPrec AndAlso c = "^") Then
'lhs.Ex = "(" + lhs.Ex + ")"
newLhs = "(" + lhs.Ex + ")"
Else
newLhs = lhs.Ex
End If
Dim newRhs As String
If rhsPrec < opPrec OrElse (rhsPrec = opPrec AndAlso c <> "^") Then
'rhs.Ex = "(" + rhs.Ex + ")"
newRhs = "(" + rhs.Ex + ")"
Else
newRhs = rhs.Ex
End If
stack.Push(New Expression(newLhs, newRhs, op))
Else
stack.Push(New Expression(token))
End If
'Print intermediate result
Console.WriteLine("{0} -> [{1}]", token, String.Join(", ", stack.Reverse().Select(Function(e) e.Ex)))
Next
Return stack.Peek().Ex
End Function
Sub Main()
Dim inputs = {"3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^"}
For Each e In inputs
Console.WriteLine("Postfix : {0}", e)
Console.WriteLine("Infix : {0}", PostfixToInfix(e))
Console.WriteLine()
Next
Console.ReadLine() 'remove before submit
End Sub
End Module
```
{{out}}
```txt
Postfix : 3 4 2 * 1 5 - 2 3 ^ ^ / +
3 -> [3]
4 -> [3, 4]
2 -> [3, 4, 2]
* -> [3, 4 * 2]
1 -> [3, 4 * 2, 1]
5 -> [3, 4 * 2, 1, 5]
- -> [3, 4 * 2, 1 - 5]
2 -> [3, 4 * 2, 1 - 5, 2]
3 -> [3, 4 * 2, 1 - 5, 2, 3]
^ -> [3, 4 * 2, 1 - 5, 2 ^ 3]
^ -> [3, 4 * 2, (1 - 5) ^ 2 ^ 3]
/ -> [3, 4 * 2 / (1 - 5) ^ 2 ^ 3]
+ -> [3 + 4 * 2 / (1 - 5) ^ 2 ^ 3]
Infix : 3 + 4 * 2 / (1 - 5) ^ 2 ^ 3
Postfix : 1 2 + 3 4 + ^ 5 6 + ^
1 -> [1]
2 -> [1, 2]
+ -> [1 + 2]
3 -> [1 + 2, 3]
4 -> [1 + 2, 3, 4]
+ -> [1 + 2, 3 + 4]
^ -> [(1 + 2) ^ (3 + 4)]
5 -> [(1 + 2) ^ (3 + 4), 5]
6 -> [(1 + 2) ^ (3 + 4), 5, 6]
+ -> [(1 + 2) ^ (3 + 4), 5 + 6]
^ -> [((1 + 2) ^ (3 + 4)) ^ (5 + 6)]
Infix : ((1 + 2) ^ (3 + 4)) ^ (5 + 6)
```
## zkl
{{trans|Go}}
```zkl
tests:=T("3 4 2 * 1 5 - 2 3 ^ ^ / +","1 2 + 3 4 + ^ 5 6 + ^");
var opa=D(
"^",T(4, True),
"*",T(3, False), "/",T(3, False),
"+",T(2, False), "-",T(2, False) );
const nPrec = 9;
foreach t in (tests) { parseRPN(t) }
fcn parseRPN(e){
println("\npostfix:", e);
stack:=L();
foreach tok in (e.split()){
println("token: ", tok);
opPrec,rAssoc:=opa.find(tok,T(Void,Void));
if(opPrec){
rhsPrec,rhsExpr := stack.pop();
lhsPrec,lhsExpr := stack.pop();
if(lhsPrec < opPrec or (lhsPrec == opPrec and rAssoc))
lhsExpr = "(" + lhsExpr + ")";
lhsExpr += " " + tok + " ";
if(rhsPrec < opPrec or (rhsPrec == opPrec and not rAssoc)){
lhsExpr += "(" + rhsExpr + ")"
} else
lhsExpr += rhsExpr;
lhsPrec = opPrec;
stack.append(T(lhsPrec,lhsExpr));
} else
stack.append(T(nPrec, tok));
foreach f in (stack){
println(0'| %d "%s"|.fmt(f.xplode()))
}
}
println("infix:", stack[0][1])
}
```
{{out}}
```txt
postfix: 3 4 2 * 1 5 - 2 3 ^ ^ / +
token: 3
9 "3"
token: 4
9 "3"
9 "4"
...
token: ^
9 "3"
3 "4 * 2"
4 "(1 - 5) ^ 2 ^ 3"
token: /
9 "3"
3 "4 * 2 / (1 - 5) ^ 2 ^ 3"
token: +
2 "3 + 4 * 2 / (1 - 5) ^ 2 ^ 3"
infix: 3 + 4 * 2 / (1 - 5) ^ 2 ^ 3
postfix: 1 2 + 3 4 + ^ 5 6 + ^
...
infix: ((1 + 2) ^ (3 + 4)) ^ (5 + 6)
```