How to resolve the algorithm Parsing/Shunting-yard algorithm step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Parsing/Shunting-yard algorithm step by step in the Nim programming language

Table of Contents

Problem Statement

Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed.

Add extra text explaining the actions and an optional comment for the action on receipt of each token.

The handling of functions and arguments is not required.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Parsing/Shunting-yard algorithm step by step in the Nim programming language

Source code in the nim programming language

import tables, strutils, strformat

type operator = tuple[prec:int, rassoc:bool]

let ops = newTable[string, operator](
  [ ("^", (4, true )),
    ("*", (3, false)),
    ("/", (3, false)),
    ("+", (2, false)),
    ("-", (2, false)) ])

proc shuntRPN(tokens:seq[string]): string =
  var stack: seq[string]
  var op:string

  for token in tokens:
    case token
    of "(": stack.add token
    of ")":
      while stack.len > 0:
        op = stack.pop()
        if op == "(": break
        result &= op & " "
    else:
      if token in ops:
        while stack.len > 0:
          op = stack[^1]  # peek stack top
          if not (op in ops): break
          if ops[token].prec > ops[op].prec or (ops[token].rassoc and (ops[token].prec == ops[op].prec)):
            break
          discard stack.pop()
          result &= op & " "
        stack.add token
      else:
        result &= token & " "
    echo fmt"""{token:5}   {join(stack," "):18} {result:25} """

  while stack.len > 0:
    result &= stack.pop() & " "
    echo fmt"""        {join(stack," "):18} {result:25} """

let input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"

echo &"for infix expression: '{input}' \n", "\nTOKEN   OP STACK           RPN OUTPUT"
echo "postfix: ", shuntRPN(input.strip.split)


  

You may also check:How to resolve the algorithm Galton box animation step by step in the Yabasic programming language
You may also check:How to resolve the algorithm Zero to the zero power step by step in the Sinclair ZX81 BASIC programming language
You may also check:How to resolve the algorithm Levenshtein distance step by step in the Simula programming language
You may also check:How to resolve the algorithm Find the last Sunday of each month step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Temperature conversion step by step in the Ada programming language