Parsing/RPN calculator algorithm: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 26:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">[Float] a
[String = ((Float, Float) -> Float)] b
b[‘+’] = (x, y) -> y + x
Line 41:
E
a.append(Float(c))
print(c‘ ’a)</langsyntaxhighlight>
 
{{out}}
Line 63:
{{trans|FORTRAN}}
For concision, only integer arithmetic is handled, but input numbers can be of any length. The formal task is not completed, but the spirit of it is.
<langsyntaxhighlight lang="360asm">* RPN calculator RC 25/01/2019
REVPOL CSECT
USING REVPOL,R13 base register
Line 165:
XDEC DS CL12
YREGS
END REVPOL</langsyntaxhighlight>
{{out}}
<pre>
Line 187:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
DEFINE PTR="CARD"
Line 314:
Put(125) PutE() ;clear the screen
Test("3 4 2 * 1 5 - 2 3 ^ ^ / +")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/RPN_calculator_algorithm.png Screenshot from Atari 8-bit computer]
Line 336:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Containers.Vectors;
 
procedure RPN_Calculator is
Line 403:
 
 
end RPN_Calculator;</langsyntaxhighlight>
 
{{out}}
Line 424:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># RPN Expression evaluator - handles numbers and + - * / ^ #
# the right-hand operand for ^ is converted to an integer #
 
Line 566:
evaluate( rpn expression )
 
)</langsyntaxhighlight>
{{out}}
<pre>
Line 587:
 
=={{header|ANSI Standard BASIC}}==
<langsyntaxhighlight ANSIlang="ansi Standardstandard BASICbasic">1000 DECLARE EXTERNAL SUB rpn
1010 PUBLIC NUMERIC R(64) ! stack
1020 PUBLIC STRING expn$ ! for keyboard input
Line 710:
2210 NEXT ptr
2220 PRINT
2230 END SUB</langsyntaxhighlight>
 
=={{header|ANTLR}}==
Line 718:
<br clear=both>
===Java===
<langsyntaxhighlight lang="java">
grammar rpnC ;
//
Line 738:
WS : (' ' | '\t'){skip()};
NEWLINE : '\r'? '\n';
</syntaxhighlight>
</lang>
Produces:
<pre>
Line 750:
{{works with|AutoHotkey_L}}
Output is in clipboard.
<langsyntaxhighlight AHKlang="ahk">evalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +")
evalRPN(s){
stack := []
Line 784:
out .= A_Space value
return subStr(out, 2)
}</langsyntaxhighlight>
{{out}}
<pre>For RPN expression: '3 4 2 * 1 5 - 2 3 ^ ^ / +'
Line 806:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> @% = &60B
RPN$ = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
Line 843:
IF SP% = 0 ERROR 100, "Stack empty"
SP% -= 1
= Stack(SP%)</langsyntaxhighlight>
{{out}}
<pre>
Line 862:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( show
= line a
. \n:?line
Line 896:
)
& out$!stack
)</langsyntaxhighlight>
Input from keyboard:
<pre>3 4 2 * 1 5 - 2 3 ^ ^ / +</pre>
Line 917:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 978:
printf("%g\n", rpn(s));
return 0;
}</langsyntaxhighlight>
 
It's also possible to parse RPN string backwards and recursively; good luck printing out your token stack ''as a table'': there isn't one.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
Line 1,033:
printf("%g\n", rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +"));
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,135:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,158:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <vector>
#include <string>
#include <sstream>
Line 1,210:
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,231:
 
=={{header|Ceylon}}==
<syntaxhighlight lang="text">import ceylon.collection {
 
ArrayList
Line 1,274:
print(calculate("3 4 2 * 1 5 - 2 3 ^ ^ / +"));
}</langsyntaxhighlight>
{{out}}
<pre>Token Operation Stack
Line 1,295:
=={{header|Clojure}}==
This would be a lot simpler and generic if we were allowed to use something other than ^ for exponentiation. ^ isn't a legal clojure symbol.
<langsyntaxhighlight lang="clojure">
(ns rosettacode.parsing-rpn-calculator-algorithm
(:require clojure.math.numeric-tower
Line 1,325:
(clojure.pprint/pprint stacks)
(print "answer:" (->> stacks last first)))
</syntaxhighlight>
</lang>
{{out}}
stacks:
Line 1,345:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% Split string by whitespace
split = iter (expr: string) yields (string)
own whitespace: string := " \r\n\t"
Line 1,417:
stream$putl(po, "Expression: " || expr)
stream$putl(po, "Result: " || f_form(evaluate_rpn(expr), 5, 5))
end start_up</langsyntaxhighlight>
{{out}}
<pre>Expression: 3 4 2 * 1 5 - 2 3 ^ ^ / +
Line 1,437:
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
IDENTIFICATION DIVISION.
PROGRAM-ID. RPN.
Line 1,565:
END-PROGRAM.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,586:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(setf (symbol-function '^) #'expt) ; Make ^ an alias for EXPT
 
(defun print-stack (token stack)
Line 1,605:
(when verbose
(print-stack current next-stack))
(rpn (cdr tokens) :stack next-stack :verbose verbose)))))</langsyntaxhighlight>
 
{{Out}}
Line 1,632:
=={{header|D}}==
{{trans|Go}}
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.typetuple;
 
void main() {
Line 1,657:
}
writeln("\nThe final value is ", stack[0]);
}</langsyntaxhighlight>
{{out}}
<pre>For postfix expression: 3 4 2 * 1 5 - 2 3 ^ ^ / +
Line 1,679:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; RPN (postfix) evaluator
 
Line 1,708:
(define S (stack 'S))
(calculator (text-parse rpn) S ))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,737:
 
=={{header|Ela}}==
<langsyntaxhighlight lang="ela">open string generic monad io
 
type OpType = Push | Operate
Line 1,778:
 
res = parse "3 4 2 * 1 5 - 2 3 ^ ^ / +" |> eval []
print_result res ::: IO</langsyntaxhighlight>
 
{{out}}
Line 1,798:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(rpn).
-export([eval/1]).
 
Line 1,840:
lists:map(fun (X) when is_integer(X) -> io:format("~12.12b ",[X]);
(X) when is_float(X) -> io:format("~12f ",[X]) end, Stack),
io:format("~n").</langsyntaxhighlight>
 
{{out}}
Line 1,862:
{{trans|OCaml}}
<p>As interactive script</p>
<langsyntaxhighlight lang="fsharp">let reduce op = function
| b::a::r -> (op a b)::r
| _ -> failwith "invalid expression"
Line 1,884:
printfn "Token Action Stack";
let ss = str.ToString().Split() |> Array.toList
List.fold interp_and_show [] ss</langsyntaxhighlight>
{{out}}
<pre>> eval "3 4 2 * 1 5 - 2 3 ^ ^ / +";;
Line 1,905:
=={{header|Factor}}==
Factor <i>is</i> a stack-based evaluator for an expression in reverse Polish notation. In the listener:
<langsyntaxhighlight lang="factor">IN: scratchpad 3 4 2 * 1 5 - 2 3 ^ ^ / +
 
--- Data stack:
3+1/8192</langsyntaxhighlight>
 
To show intermediate steps:
<langsyntaxhighlight lang="factor">{ 3 4 2 * 1 5 - 2 3 ^ ^ / + }
[ dup pprint bl 1quotation call get-datastack . ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 1,935:
{{works with|gforth|0.7.3}}
Forth is stack-based, so evaluation is direct:
<langsyntaxhighlight lang="forth">: ^ over swap 1 ?do over * loop nip ;
s" 3 4 2 * 1 5 - 2 3 ^ ^ / +" evaluate .</langsyntaxhighlight>
 
To show intermediate steps:
<langsyntaxhighlight lang="forth">: ^ over swap 1 ?do over * loop nip ;
: detail
begin
Line 1,949:
2drop
;
detail 3 4 2 * 1 5 - 2 3 ^ ^ / +</langsyntaxhighlight>
 
{{out}}
Line 1,974:
The method is simple (the whole point of RPN) and the function prints a schedule of actions at each step. Possibly this semi-tabular output is what is meant by "as a table". Conveniently, all the operators take two operands and return one, so the SP accountancy can be shared. Unlike ! for example.
 
The source style is essentially F77 except for the trivial use of the PARAMETER statement, and CYCLE to GO TO the end of the loop when a space is encountered. With the introduction of unfixed-format source style came also the possible use of semicolons to cram more than one statement part on a line so that the CASE and its action statement can be spread across the page rather than use two lines in alternation: for this case a tabular layout results that is easier to read and check. Because the F90 MODULE protocol is not used, the function's type should be declared in the calling routine but the default type suffices.<langsyntaxhighlight Fortranlang="fortran"> REAL FUNCTION EVALRP(TEXT) !Evaluates a Reverse Polish string.
Caution: deals with single digits only.
CHARACTER*(*) TEXT !The RPN string.
Line 2,021:
V = EVALRP("3 4 2 * 1 5 - 2 3 ^ ^ / +") !The specified example.
WRITE (6,*) "Result is...",V
END</langsyntaxhighlight>
 
Output...
Line 2,044:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">#define NULL 0
 
type node
Line 2,124:
end select
print_stack(@StackHead)
wend</langsyntaxhighlight>
{{out}}<pre>
Token: 3 Operation push Stack <--- 3
Line 2,142:
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">def evaluate( expr ) =
stack = []
 
Line 2,160:
 
res = evaluate( '3 4 2 * 1 5 - 2 3 ^ ^ / +' )
println( res + (if res is Integer then '' else " or ${float(res)}") )</langsyntaxhighlight>
 
{{out}}
Line 2,183:
=={{header|Go}}==
No error checking.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,225:
}
fmt.Println("\nThe final value is", stack[0])
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,249:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def evaluateRPN(expression) {
def stack = [] as Stack
def binaryOp = { action -> return { action.call(stack.pop(), stack.pop()) } }
Line 2,267:
assert stack.size() == 1 : "Unbalanced Expression: $expression ($stack)"
stack.pop()
}</langsyntaxhighlight>
Test
<langsyntaxhighlight lang="groovy">println evaluateRPN('3 4 2 * 1 5 - 2 3 ^ ^ / +')</langsyntaxhighlight>
{{out}}
<pre>3: [3]
Line 2,288:
=={{header|Haskell}}==
Pure RPN calculator
<langsyntaxhighlight Haskelllang="haskell">calcRPN :: String -> [Double]
calcRPN = foldl interprete [] . words
 
Line 2,300:
"*" -> x * y:s
"/" -> y / x:s
"^" -> y ** x:s</langsyntaxhighlight>
 
<pre>λ> calcRPN "3 4 +"
Line 2,313:
''Pure logging''. Log as well as a result could be used as a data.
 
<langsyntaxhighlight lang="haskell">calcRPNLog :: String -> ([Double],[(String, [Double])])
calcRPNLog input = mkLog $ zip commands $ tail result
where result = scanl interprete [] commands
commands = words input
mkLog [] = ([], [])
mkLog res = (snd $ last res, res)</langsyntaxhighlight>
 
<pre>λ> calcRPNLog "3 4 +"
Line 2,339:
 
''Logging as a side effect.'' Calculator returns result in IO context:
<langsyntaxhighlight lang="haskell">import Control.Monad (foldM)
 
calcRPNIO :: String -> IO [Double]
Line 2,345:
 
verbose f s x = write (x ++ "\t" ++ show res ++ "\n") >> return res
where res = f s x</langsyntaxhighlight>
 
<pre>λ> calcRPNIO "3 4 +"
Line 2,372:
 
Some universal definitions:
<langsyntaxhighlight lang="haskell">class Monad m => Logger m where
write :: String -> m ()
 
Line 2,381:
show y ++ " ==> " ++
show res ++ "\n") >> return res
where res = f x y</langsyntaxhighlight>
 
The use case:
<langsyntaxhighlight lang="haskell">calcRPNM :: Logger m => String -> m [Double]
calcRPNM = foldM (verbose interprete) [] . words</langsyntaxhighlight>
 
{{out}} in REPL
Line 2,408:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
EvalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +")
end
Line 2,440:
every (s := "[ ") ||:= !L || " "
return s || "]"
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 2,466:
 
Our implementation will be a monadic verb: it will take a single argument, which contains both the accumulated stack and the tokens to be processed. First, create initial state of the input:
<langsyntaxhighlight Jlang="j"> a: , <;._1 ' ' , '3 4 2 * 1 5 - 2 3 ^ ^ / +'
┌┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐
││3│4│2│*│1│5│-│2│3│^│^│/│+│
└┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘</langsyntaxhighlight>
As an example, let's also add monadic operation _ which inverses the sign of the stack top element.
 
Line 2,485:
As a side effect, "consume" is going to print the resulting stack,
so running "consume" once for each token will produce intermediate states of the stack.
<langsyntaxhighlight Jlang="j"> isOp=: '_+-*/^' e.~ {.@>@{.
mo=: 1 :'(}: , u@{:) @ ['
dy=: 1 :'(_2&}. , u/@(_2&{.)) @ ['
Line 2,516:
┌─┐
│1│
└─┘</langsyntaxhighlight>
 
=== Alternate Implementation ===
 
<langsyntaxhighlight Jlang="j">rpn=: 3 :0
queue=. |.3 :'|.3 :y 0'::]each;: y
op=. 1 :'2 (u~/@:{.,}.)S:0 ,@]'
Line 2,526:
choose=. ((;:'+-*/^')&i.@[)
,ops@.choose/queue
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> rpn '3 4 2 * 1 5 - 2 3 ^ ^ / +'
3.00012</langsyntaxhighlight>
 
To see intermediate result stacks, use this variant (the only difference is the definition of 'op'):
 
<langsyntaxhighlight Jlang="j">rpnD=: 3 :0
queue=. |.3 :'|.3 :y 0'::]each;: y
op=. 1 :'2 (u~/@:{.,}.)S:0 ,@([smoutput)@]'
Line 2,541:
choose=. ((;:'+-*/^')&i.@[)
,ops@.choose/queue
)</langsyntaxhighlight>
 
In other words:
 
<langsyntaxhighlight Jlang="j"> rpnD '3 4 2 * 1 5 - 2 3 ^ ^ / +'
┌─────┐
│2 4 3│
Line 2,554:
65536 8 3
0.00012207 3
3.00012</langsyntaxhighlight>
 
Note that the seed stack is boxed while computed stacks are not.
Line 2,564:
{{works with|Java|1.5+}}
Supports multi-digit numbers and negative numbers.
<langsyntaxhighlight lang="java5">
import java.util.LinkedList;
 
Line 2,620:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Input Operation Stack after
Line 2,639:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">
const e = '3 4 2 * 1 5 - 2 3 ^ ^ / +';
const s = [], tokens = e.split(' ');
Line 2,666:
throw new Error(`${s}: insufficient operators.`);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,686:
=={{header|Julia}}==
(This code takes advantage of the fact that all of the operands and functions in the specified RPN syntax are valid Julia expressions, so we can use the built-in <code>parse</code> and <code>eval</code> functions to turn them into numbers and the corresponding Julia functions.)
<langsyntaxhighlight lang="julia">function rpn(s)
stack = Any[]
for op in map(eval, map(parse, split(s)))
Line 2,701:
return stack[1]
end
rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +")</langsyntaxhighlight>
{{out}}
<pre>3: 3
Line 2,719:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun rpnCalculate(expr: String) {
Line 2,758:
val expr = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
rpnCalculate(expr)
}</langsyntaxhighlight>
 
{{out}}
Line 2,783:
 
==[[header|Lambdatalk]]==
<syntaxhighlight lang="scheme">
<lang Scheme>
{calc 3 4 2 * 1 5 - 2 3 pow pow / +}
->
Line 2,863:
- "W.equal?" which test the equality between two words,
- and the "or" boolean function.
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
global stack$
 
Line 2,952:
stack$=mid$(stack$,instr(stack$,"|")+1)
end function
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,978:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
local stack = {}
function push( a ) table.insert( stack, 1, a ) end
Line 3,030:
--[[ entry point ]]--
calc( "3 4 2 * 1 5 - 2 3 ^ ^ / +" )
calc( "22 11 *" )</langsyntaxhighlight>
{{out}}
<pre>
Line 3,058:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Rpn_Calc {
Rem Form 80,60
Line 3,095:
}
Rpn_Calc
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,161:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
(This code takes advantage of the fact that all of the operands and functions in the specified RPN syntax can be used to form valid Mathematica expressions, so we can use the built-in ToExpression function to turn them into numbers and the corresponding Mathematica functions. Note that we need to add braces around arguments, otherwise "-4^8" would be parsed as "-(4^8)" instead of "(-4)^8".)
<langsyntaxhighlight Mathematicalang="mathematica">calc[rpn_] :=
Module[{tokens = StringSplit[rpn], s = "(" <> ToString@InputForm@# <> ")" &, op, steps},
op[o_, x_, y_] := ToExpression[s@x <> o <> s@y];
Line 3,169:
Grid[Transpose[{# <> ":" & /@ tokens,
StringRiffle[ToString[#, InputForm] & /@ #] & /@ steps}]]];
Print[calc["3 4 2 * 1 5 - 2 3 ^ ^ / +"]];</langsyntaxhighlight>
{{out}}
<pre>3: 3
Line 3,199:
=={{header|Maxima}}==
 
<langsyntaxhighlight Maximalang="maxima">rmod(i, j) := mod(j, i)$
rpow(x, y) := y^x$
 
Line 3,237:
)$
 
rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +"), numer;</langsyntaxhighlight>
 
===Output===
<syntaxhighlight lang="text">(%i5) ev(rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +"),numer)
3 : [3]
4 : [4, 3]
Line 3,254:
/ : [1.220703125e-4, 3]
+ : [3.0001220703125]
(%o5) 3.0001220703125</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">RPN = function(inputText)
tokens = inputText.split
stack = []
Line 3,278:
end function
 
print RPN("3 4 2 * 1 5 - 2 3 ^ ^ / +")</langsyntaxhighlight>
 
{{out}}
Line 3,301:
 
{{works with|GNU TROFF|1.22.2}}
<langsyntaxhighlight Nlang="n/t/roff">.ig
RPN parser implementation in TROFF
 
Line 3,414:
.el .RPNPRINT
..
.RPNPARSE 3 4 2 * 1 5 - 2 3 ^ ^ / + \" Our input expression</langsyntaxhighlight>
 
====Output====
<syntaxhighlight lang="text"> 3
3 4
3 4 2
Line 3,430:
3 0
3
3</langsyntaxhighlight>
 
===Modern version===
Line 3,437:
{{works with|GNU Troff|1.22.2}}
 
<langsyntaxhighlight Nlang="n/t/roff">.ig
===========================
Array implementation
Line 3,525:
..
.rpn 3 4 2 * 1 5 - 2 3 ^ ^ / +
.stack.dump</langsyntaxhighlight>
 
====Output====
<syntaxhighlight lang="text">3
3 4
3 4 2
Line 3,541:
3 0
3
3</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 3,633:
calc = stack.toString
return calc
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,657:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import math, rdstdin, strutils, tables
 
type Stack = seq[float]
Line 3,726:
for i, y in x:
stdout.write y.alignLeft(maxColWidths[i])
echo ""</langsyntaxhighlight>
 
{{out}}
Line 3,746:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use IO;
use Struct;
Line 3,810:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,832:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">(* binop : ('a -> 'a -> 'a) -> 'a list -> 'a list *)
let binop op = function
| b::a::r -> (op a b)::r
Line 3,858:
Printf.printf "Token\tAction\tStack\n";
let ss = Str.(split (regexp_string " ") str) in
List.fold_left interp_and_show [] ss</langsyntaxhighlight>
 
Evaluation of the test expression:
Line 3,884:
Oforth uses RPN and natively parse RPN.
 
<langsyntaxhighlight Oforthlang="oforth">"3 4 2 * 1 5 - 2 3 ^ ^ / +" eval println</langsyntaxhighlight>
 
{{out}}
Line 3,893:
To show the changes in the stack, we can use .l after evaluating each word :
 
<langsyntaxhighlight Oforthlang="oforth">: rpn(s) { s words apply(#[ eval .l ]) }
 
rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +")</langsyntaxhighlight>
 
{{out}}
Line 3,915:
 
=={{header|ooRexx}}==
<langsyntaxhighlight ooRexxlang="oorexx">/* ooRexx *************************************************************
* 10.11.2012 Walter Pachl translated from PL/I via REXX
**********************************************************************/
Line 3,946:
end
Say 'The reverse polish expression = 'expr
Say 'The evaluated expression = 'st~pull</langsyntaxhighlight>
{{out}}
<pre>
Line 3,964:
Due to the nature of the language, it is not trivial to process an expression as a simple space-separated string. Though, this could be done if one calls an external shell program such as <code>sed</code> and pipes the result back hither.
 
<langsyntaxhighlight lang="parigp">estack = [];
 
epush(x) = {
Line 4,002:
};
 
parseRPN([3, 4, 2, "*", 1, 5, "-", 2, 3, "^", "^", "/", "+"]); \\ Our input expression</langsyntaxhighlight>
 
===Output===
<syntaxhighlight lang="text">[3]
[3, 4]
[3, 4, 2]
Line 4,017:
[3, 8, 65536]
[3, 1/8192]
[24577/8192]</langsyntaxhighlight>
 
Whenever possible, PARI/GP tries to manipulate and return results in the simplest form it can. In this case, it deems fractions the most suitable form of output. Nonetheless, converting the fraction <code>24577/8192</code> yields <code>3.0001220703125</code> as expected.
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 4,048:
say $a;
eval $a;
}</langsyntaxhighlight>
{{out}}
<pre>(4)*(2)
Line 4,059:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">evalRPN</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 4,078:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">evalRPN</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"3 4 2 * 1 5 - 2 3 ^ ^ / +"</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,097:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
<?php
function rpn($postFix){
Line 4,143:
echo "Compute Value: " . rpn("3 4 2 * 1 5 - 2 3 ^ ^ / + ");
?>
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,165:
=={{header|PicoLisp}}==
This is an integer-only calculator:
<langsyntaxhighlight PicoLisplang="picolisp">(de rpnCalculator (Str)
(let (^ ** Stack) # Define '^' from the built-in '**'
(prinl "Token Stack")
Line 4,176:
(space 6)
(println Stack) )
(println (car Stack)) ) )</langsyntaxhighlight>
Test (note that the top-of-stack is in the left-most position):
<langsyntaxhighlight PicoLisplang="picolisp">: (rpnCalculator "3 4 2 * 1 5 - 2 3 \^ \^ / +")
Token Stack
3 (3)
Line 4,194:
+ (3)
3
-> 3</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">Calculator: procedure options (main); /* 14 Sept. 2012 */
declare expression character (100) varying initial ('');
declare ch character (1);
Line 4,228:
put skip list ('The evaluated expression = ' || stack);
 
end Calculator;</langsyntaxhighlight>
<pre>
Stack contents:
Line 4,256:
 
=={{header|PL/SQL}}==
<langsyntaxhighlight lang="plsql">create or replace function rpn_calc(str varchar2) return number as
type num_aa is table of number index by pls_integer;
type num_stack is record (a num_aa, top pls_integer default 0);
Line 4,301:
return pop(ns);
end rpn_calc;
/</langsyntaxhighlight>
 
Testing:
 
<langsyntaxhighlight lang="plsql">begin
dbms_output.put_line(chr(10) || 'Result: ' || rpn_calc('3 4 2 * 1 5 - 2 3 ^ ^ / +'));
end;
/</langsyntaxhighlight>
 
Output:
Line 4,334:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Invoke-Rpn
{
Line 4,467:
 
Invoke-Rpn -Expression "3 4 2 * 1 5 - 2 3 ^ ^ / +" -DisplayState
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,491:
=={{header|Prolog}}==
Works with SWI-Prolog.
<langsyntaxhighlight Prologlang="prolog">rpn(L) :-
writeln('Token Action Stack'),
parse(L, [],[X] ,[]),
Line 4,537:
is_op(45, X, Y, V) :- V is X-Y.
is_op(47, X, Y, V) :- V is X/Y.
is_op(94, X, Y, V) :- V is X**Y.</langsyntaxhighlight>
{{out}}
<pre>5 ?- rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +").
Line 4,560:
=={{header|Python}}==
=== Version 1 ===
<langsyntaxhighlight lang="python">def op_pow(stack):
b = stack.pop(); a = stack.pop()
stack.append( a ** b )
Line 4,618:
print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
 
print('\n The final output value is: %r' % rp[-1][2])</langsyntaxhighlight>
 
{{out}}
Line 4,642:
=== Version 2 ===
 
<langsyntaxhighlight lang="python">a=[]
b={'+': lambda x,y: y+x, '-': lambda x,y: y-x, '*': lambda x,y: y*x,'/': lambda x,y:y/x,'^': lambda x,y:y**x}
for c in '3 4 2 * 1 5 - 2 3 ^ ^ / +'.split():
if c in b: a.append(b[c](a.pop(),a.pop()))
else: a.append(float(c))
print c, a</langsyntaxhighlight>
 
{{out}}
Line 4,674:
(If the gentle gatekeepers will permit a moment of shameless self-promotion… If you are interested in stack processors or concatenative languages, you may wish to consider that Quackery was designed with the intent of being an entry level language suitable for educational and hobbyist use, accessible at the code level by virtue of being coded in (mostly) non-idiomatic Python (24k source) and Quackery (another 24k of course) with the Python code emphasising a straightforward approach and the use of simple algorithms for the sake of legibility in preference to efficiency.)
 
<syntaxhighlight lang="quackery">
<lang Quackery>
[ stack ] is switch.arg ( --> [ )
 
Line 4,710:
 
$ "3 4 2 * 1 5 - 2 3 ^ ^ / +" rpncalc
say "Result: " echo</langsyntaxhighlight>
 
{{out}}
Line 4,731:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
Line 4,747:
(reverse (cons x s)))])))
 
</syntaxhighlight>
</lang>
Test case
<pre>
Line 4,768:
 
Reading from a string:
<langsyntaxhighlight lang="racket">
(calculate-RPN (in-port read (open-input-string "3.0 4 2 * 1 5 - 2 3 ^ ^ / +")))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-25}}
<syntaxhighlight lang="raku" line>
<lang perl6>
my $proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +';
Line 4,798:
RPN.new.run($proggie);
</syntaxhighlight>
</lang>
{{out}}
<pre>3 ()
Line 4,817:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 09.11.2012 Walter Pachl translates from PL/I
**********************************************************************/
Line 4,869:
End
Say ol
Return</langsyntaxhighlight>
{{out}}
<pre>
Line 4,888:
:::: <big><big> 3.0 &nbsp; .4e1 &nbsp; 2e0 &nbsp; * &nbsp; +1. &nbsp; 5 &nbsp; - &nbsp; 2 &nbsp; 3 &nbsp; ** &nbsp; ** &nbsp; / &nbsp; + </big></big>
which is the essentially the same as the default used by the REXX program.
<langsyntaxhighlight REXXlang="rexx">/*REXX program evaluates a ═════ Reverse Polish notation (RPN) ═════ expression. */
parse arg x /*obtain optional arguments from the CL*/
if x='' then x= "3 4 2 * 1 5 - 2 3 ^ ^ / +" /*Not specified? Then use the default.*/
Line 4,916:
else exit $ /*return the answer ───► the invoker.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: if showSteps then say center(arg(1), L) left(space($), L); return</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 4,951:
::* &nbsp; allows remainder division &nbsp; <big>//</big>
::* &nbsp; allows concatenation &nbsp; <big>||</big>
<langsyntaxhighlight REXXlang="rexx">/*REXX program evaluates a ═════ Reverse Polish notation (RPN) ═════ expression. */
parse arg x /*obtain optional arguments from the CL*/
if x='' then x= "3 4 2 * 1 5 - 2 3 ^ ^ / +" /*Not specified? Then use the default.*/
Line 4,993:
/*──────────────────────────────────────────────────────────────────────────────────────*/
isBit: return arg(1)==0 | arg(1)==1 /*returns 1 if arg1 is a binary bit*/
show: if showSteps then say center(arg(1), L) left(space($), L); return</langsyntaxhighlight>
'''output''' &nbsp; is identical to the 2<sup>nd</sup> REXX version.
<br><br>
Line 4,999:
=={{header|Ruby}}==
See [[Parsing/RPN/Ruby]]
<langsyntaxhighlight lang="ruby">rpn = RPNExpression("3 4 2 * 1 5 - 2 3 ^ ^ / +")
value = rpn.eval</langsyntaxhighlight>
{{out}}
<pre>for RPN expression: 3 4 2 * 1 5 - 2 3 ^ ^ / +
Line 5,020:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">prn$ = "3 4 2 * 1 5 - 2 3 ^ ^ / + "
 
j = 0
Line 5,053:
if op$ = "+" then op = a + b
if op$ = "-" then op = a - b
end function</langsyntaxhighlight>
<pre>Push Num 3 to stack: 3
Push Num 4 to stack: 3 4
Line 5,069:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn rpn(text: &str) -> f64 {
let tokens = text.split_whitespace();
let mut stack: Vec<f64> = vec![];
Line 5,122:
 
println!("\nresult: {}", rpn(text));
}</langsyntaxhighlight>
{{out}}
<pre>input operation stack
Line 5,143:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object RPN {
val PRINT_STACK_CONTENTS: Boolean = true
 
Line 5,182:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,202:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">var proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +'
 
class RPN(arr=[]) {
Line 5,234:
}
 
RPN.new.run(proggie)</langsyntaxhighlight>
{{out}}
<pre>
Line 5,260:
No attempt is made to check for invalid syntax, stack overflow or underflow, etc.
 
<langsyntaxhighlight lang="basic"> 10 DIM S(5)
20 LET P=1
30 INPUT E$
Line 5,287:
260 LET S(P-2)=VAL (STR$ S(P-2)+W$+STR$ S(P-1))
270 LET P=P-1
280 GOTO 180</langsyntaxhighlight>
{{in}}
<pre>3 4 2 * 1 5 - 2 3 ** ** / +</pre>
Line 5,307:
=={{header|Swift}}==
{{trans|Go}}
<langsyntaxhighlight Swiftlang="swift">let opa = [
"^": (prec: 4, rAssoc: true),
"*": (prec: 3, rAssoc: false),
Line 5,364:
input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
"infix: \(input)"
"postfix: \(parseInfix(input))"</langsyntaxhighlight>
{{out}}
<pre>"postfix: 3 4 2 * 1 5 - 2 3 ^ ^ / +"</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl"># Helper
proc pop stk {
upvar 1 $stk s
Line 5,417:
}
 
puts [evaluate {3 4 2 * 1 5 - 2 3 ^ ^ / +}]</langsyntaxhighlight>
{{out}}
<pre>
Line 5,441:
Technically, this implementation uses a string to represent a stack and lines to delimit each item of the stack, not spaces as you might expect. However, the input is parsed pretty much as a space-separated argument string, but only with the asterisk quoted.
 
<langsyntaxhighlight lang="bash">#!/bin/sh
 
exp() {
Line 5,505:
}
 
rpn 3 4 2 '*' 1 5 '-' 2 3 '^' '^' '/' '+'</langsyntaxhighlight>
 
===Output===
<syntaxhighlight lang="text">3 : 3
4 : 3 4
2 : 3 4 2
Line 5,521:
/ : 3 0
+ : 3
3</langsyntaxhighlight>
 
=={{header|VBA}}==
Line 5,527:
{{trans|Liberty BASIC}}
 
<langsyntaxhighlight VBAlang="vba">Global stack$
Function RPN(expr$)
Line 5,612:
pop$ = Split(stack$, "|")(0)
stack$ = Mid$(stack$, InStr(stack$, "|") + 1)
End Function</langsyntaxhighlight>
 
{{out}}
Line 5,638:
{{trans|C}}
Updated to Vlang version 0.2.2
<langsyntaxhighlight lang="go">import math
 
const (
Line 5,727:
println('\nResult: $result')
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Input: 3 4 2 * 1 5 - 2 3 ^ ^ / +
Line 5,750:
{{trans|Kotlin}}
{{libheader|Wren-seq}}
<langsyntaxhighlight lang="ecmascript">import "/seq" for Stack
 
var rpnCalculate = Fn.new { |expr|
Line 5,781:
 
var expr = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
rpnCalculate.call(expr)</langsyntaxhighlight>
 
{{out}}
Line 5,809:
{{trans|VBA}}
 
<syntaxhighlight lang="xojo">
<lang Xojo>
Function RPN(expr As String) As String
Line 5,866:
Return stack(2)
End Function</langsyntaxhighlight>
 
 
Line 5,893:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var ops=D("^",True, "*",'*, "/",'/, "+",'+, "-",'-);
 
fcn parseRPN(e){
Line 5,910:
}
println("result: ", stack[0])
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">tests:=T("3 4 2 * 1 5 - 2 3 ^ ^ / +");
foreach t in (tests) { parseRPN(t) }</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits