How to resolve the algorithm Parsing/RPN to infix conversion step by step in the zkl 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 zkl 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 zkl programming language

Source code in the zkl programming language

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])
}

  

You may also check:How to resolve the algorithm Vogel's approximation method step by step in the Python programming language
You may also check:How to resolve the algorithm Set step by step in the OCaml programming language
You may also check:How to resolve the algorithm Repeat step by step in the МК-61/52 programming language
You may also check:How to resolve the algorithm Perfect shuffle step by step in the VBA programming language
You may also check:How to resolve the algorithm Numbers which are the cube roots of the product of their proper divisors step by step in the EasyLang programming language