How to resolve the algorithm Parsing/RPN calculator algorithm step by step in the jq programming language

Published on 12 May 2024 09:40 PM
#Jq

How to resolve the algorithm Parsing/RPN calculator algorithm step by step in the jq programming language

Table of Contents

Problem Statement

Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table.

3 4 2 * 1 5 - 2 3 ^ ^ / +

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Parsing/RPN calculator algorithm step by step in the jq programming language

Source code in the jq programming language

# Input: an array representing a stack, with .[-1] being its top.
# Output: the updated array after applying `op`
def rpn(op):
  def two: .[-2:];
  def update($x): (.[:-2] + [$x]);
  if length<=1 then .
  elif op == "+" then update(two | add)
  elif op == "*" then update(two | (.[0] * .[1]))
  elif op == "/" then update(two | (.[0] / .[1]))
  elif op == "-" then update(two | (.[0] - .[1]))
  elif op == "^" then update(two | (pow(.[0]; .[1])))
  else ("ignoring unrecognized op \(op)" | debug) as $debug | .
  end;

def eval:
   foreach .[] as $item ([];
      if ($item | type) == "number" then . + [$item]
      else rpn($item)
      end;
      "\($item) => \(.)" ) ;

"3 4 2 * 1 5 - 2 3 ^ ^ / +"
| split(" ") | map( (try tonumber) // .)
| eval

  

You may also check:How to resolve the algorithm Reverse words in a string step by step in the Swift programming language
You may also check:How to resolve the algorithm Search a list of records step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Legendre prime counting function step by step in the Crystal programming language
You may also check:How to resolve the algorithm Mayan numerals step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm HTTP step by step in the MATLAB / Octave programming language