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

Published on 12 May 2024 09:40 PM

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

Source code in the ceylon programming language

import ceylon.collection {

	ArrayList
}

shared void run() {
	
	value ops = map {
		"+" -> plus,
		"*" -> times,
		"-" -> ((Float a, Float b) => a - b),
		"/" -> ((Float a, Float b) => a / b),
		"^" -> ((Float a, Float b) => a ^ b)
	};
	
	void printTableRow(String|Float token, String description, {Float*} stack) {
		print("``token.string.padTrailing(8)````description.padTrailing(30)````stack``");
	}
	
	function calculate(String input) {
		
		value stack = ArrayList();
		value tokens = input.split().map((String element) 
			=> if(ops.keys.contains(element)) then element else parseFloat(element));
		
		print("Token   Operation                     Stack");
		
		for(token in tokens.coalesced) {
			if(is Float token) {
				stack.push(token);
				printTableRow(token, "push", stack);
			} else if(exists op = ops[token], exists first = stack.pop(), exists second = stack.pop()) {
				value result = op(second, first);
				stack.push(result);
				printTableRow(token, "perform ``token`` on ``formatFloat(second, 1, 1)`` and ``formatFloat(first, 1, 1)``", stack);
			} else {
				throw Exception("bad syntax");
			}
		}
		return stack.pop();
	}
	
	print(calculate("3 4 2 * 1 5 - 2 3 ^ ^ / +"));
}


  

You may also check:How to resolve the algorithm Reflection/List methods step by step in the Factor programming language
You may also check:How to resolve the algorithm HTTPS step by step in the Erlang programming language
You may also check:How to resolve the algorithm Enforced immutability step by step in the Racket programming language
You may also check:How to resolve the algorithm Arithmetic/Complex step by step in the ALGOL W programming language
You may also check:How to resolve the algorithm Keyboard input/Keypress check step by step in the Tcl programming language