Parsing/RPN calculator algorithm: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 26:
{{trans|Python}}
<
[String = ((Float, Float) -> Float)] b
b[‘+’] = (x, y) -> y + x
Line 41:
E
a.append(Float(c))
print(c‘ ’a)</
{{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.
<
REVPOL CSECT
USING REVPOL,R13 base register
Line 165:
XDEC DS CL12
YREGS
END REVPOL</
{{out}}
<pre>
Line 187:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<
DEFINE PTR="CARD"
Line 314:
Put(125) PutE() ;clear the screen
Test("3 4 2 * 1 5 - 2 3 ^ ^ / +")
RETURN</
{{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}}==
<
procedure RPN_Calculator is
Line 403:
end RPN_Calculator;</
{{out}}
Line 424:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<
# the right-hand operand for ^ is converted to an integer #
Line 566:
evaluate( rpn expression )
)</
{{out}}
<pre>
Line 587:
=={{header|ANSI Standard BASIC}}==
<
1010 PUBLIC NUMERIC R(64) ! stack
1020 PUBLIC STRING expn$ ! for keyboard input
Line 710:
2210 NEXT ptr
2220 PRINT
2230 END SUB</
=={{header|ANTLR}}==
Line 718:
<br clear=both>
===Java===
<
grammar rpnC ;
//
Line 738:
WS : (' ' | '\t'){skip()};
NEWLINE : '\r'? '\n';
</syntaxhighlight>
Produces:
<pre>
Line 750:
{{works with|AutoHotkey_L}}
Output is in clipboard.
<
evalRPN(s){
stack := []
Line 784:
out .= A_Space value
return subStr(out, 2)
}</
{{out}}
<pre>For RPN expression: '3 4 2 * 1 5 - 2 3 ^ ^ / +'
Line 806:
=={{header|BBC BASIC}}==
<
RPN$ = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
Line 843:
IF SP% = 0 ERROR 100, "Stack empty"
SP% -= 1
= Stack(SP%)</
{{out}}
<pre>
Line 862:
=={{header|Bracmat}}==
<
= line a
. \n:?line
Line 896:
)
& out$!stack
)</
Input from keyboard:
<pre>3 4 2 * 1 5 - 2 3 ^ ^ / +</pre>
Line 917:
=={{header|C}}==
<
#include <stdlib.h>
#include <string.h>
Line 978:
printf("%g\n", rpn(s));
return 0;
}</
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.
<
#include <stdlib.h>
#include <ctype.h>
Line 1,033:
printf("%g\n", rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +"));
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 1,135:
}
}
}</
{{out}}
<pre>
Line 1,158:
=={{header|C++}}==
<
#include <string>
#include <sstream>
Line 1,210:
return 0;
}</
{{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 ^ ^ / +"));
}</
{{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.
<
(ns rosettacode.parsing-rpn-calculator-algorithm
(:require clojure.math.numeric-tower
Line 1,325:
(clojure.pprint/pprint stacks)
(print "answer:" (->> stacks last first)))
</syntaxhighlight>
{{out}}
stacks:
Line 1,345:
=={{header|CLU}}==
<
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</
{{out}}
<pre>Expression: 3 4 2 * 1 5 - 2 3 ^ ^ / +
Line 1,437:
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. RPN.
Line 1,565:
END-PROGRAM.
</syntaxhighlight>
{{out}}
<pre>
Line 1,586:
=={{header|Common Lisp}}==
<
(defun print-stack (token stack)
Line 1,605:
(when verbose
(print-stack current next-stack))
(rpn (cdr tokens) :stack next-stack :verbose verbose)))))</
{{Out}}
Line 1,632:
=={{header|D}}==
{{trans|Go}}
<
void main() {
Line 1,657:
}
writeln("\nThe final value is ", stack[0]);
}</
{{out}}
<pre>For postfix expression: 3 4 2 * 1 5 - 2 3 ^ ^ / +
Line 1,679:
=={{header|EchoLisp}}==
<
;; RPN (postfix) evaluator
Line 1,708:
(define S (stack 'S))
(calculator (text-parse rpn) S ))
</syntaxhighlight>
{{out}}
<pre>
Line 1,737:
=={{header|Ela}}==
<
type OpType = Push | Operate
Line 1,778:
res = parse "3 4 2 * 1 5 - 2 3 ^ ^ / +" |> eval []
print_result res ::: IO</
{{out}}
Line 1,798:
=={{header|Erlang}}==
<
-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").</
{{out}}
Line 1,862:
{{trans|OCaml}}
<p>As interactive script</p>
<
| 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</
{{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:
<
--- Data stack:
3+1/8192</
To show intermediate steps:
<
[ dup pprint bl 1quotation call get-datastack . ] each</
{{out}}
<pre>
Line 1,935:
{{works with|gforth|0.7.3}}
Forth is stack-based, so evaluation is direct:
<
s" 3 4 2 * 1 5 - 2 3 ^ ^ / +" evaluate .</
To show intermediate steps:
<
: detail
begin
Line 1,949:
2drop
;
detail 3 4 2 * 1 5 - 2 3 ^ ^ / +</
{{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.<
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</
Output...
Line 2,044:
=={{header|FreeBASIC}}==
<
type node
Line 2,124:
end select
print_stack(@StackHead)
wend</
{{out}}<pre>
Token: 3 Operation push Stack <--- 3
Line 2,142:
=={{header|FunL}}==
<
stack = []
Line 2,160:
res = evaluate( '3 4 2 * 1 5 - 2 3 ^ ^ / +' )
println( res + (if res is Integer then '' else " or ${float(res)}") )</
{{out}}
Line 2,183:
=={{header|Go}}==
No error checking.
<
import (
Line 2,225:
}
fmt.Println("\nThe final value is", stack[0])
}</
{{out}}
<pre>
Line 2,249:
=={{header|Groovy}}==
<
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()
}</
Test
<
{{out}}
<pre>3: [3]
Line 2,288:
=={{header|Haskell}}==
Pure RPN calculator
<
calcRPN = foldl interprete [] . words
Line 2,300:
"*" -> x * y:s
"/" -> y / x:s
"^" -> y ** x:s</
<pre>λ> calcRPN "3 4 +"
Line 2,313:
''Pure logging''. Log as well as a result could be used as a data.
<
calcRPNLog input = mkLog $ zip commands $ tail result
where result = scanl interprete [] commands
commands = words input
mkLog [] = ([], [])
mkLog res = (snd $ last res, res)</
<pre>λ> calcRPNLog "3 4 +"
Line 2,339:
''Logging as a side effect.'' Calculator returns result in IO context:
<
calcRPNIO :: String -> IO [Double]
Line 2,345:
verbose f s x = write (x ++ "\t" ++ show res ++ "\n") >> return res
where res = f s x</
<pre>λ> calcRPNIO "3 4 +"
Line 2,372:
Some universal definitions:
<
write :: String -> m ()
Line 2,381:
show y ++ " ==> " ++
show res ++ "\n") >> return res
where res = f x y</
The use case:
<
calcRPNM = foldM (verbose interprete) [] . words</
{{out}} in REPL
Line 2,408:
=={{header|Icon}} and {{header|Unicon}}==
<
EvalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +")
end
Line 2,440:
every (s := "[ ") ||:= !L || " "
return s || "]"
end</
{{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:
<
┌┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐
││3│4│2│*│1│5│-│2│3│^│^│/│+│
└┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘</
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.
<
mo=: 1 :'(}: , u@{:) @ ['
dy=: 1 :'(_2&}. , u/@(_2&{.)) @ ['
Line 2,516:
┌─┐
│1│
└─┘</
=== Alternate Implementation ===
<
queue=. |.3 :'|.3 :y 0'::]each;: y
op=. 1 :'2 (u~/@:{.,}.)S:0 ,@]'
Line 2,526:
choose=. ((;:'+-*/^')&i.@[)
,ops@.choose/queue
)</
Example use:
<
3.00012</
To see intermediate result stacks, use this variant (the only difference is the definition of 'op'):
<
queue=. |.3 :'|.3 :y 0'::]each;: y
op=. 1 :'2 (u~/@:{.,}.)S:0 ,@([smoutput)@]'
Line 2,541:
choose=. ((;:'+-*/^')&i.@[)
,ops@.choose/queue
)</
In other words:
<
┌─────┐
│2 4 3│
Line 2,554:
65536 8 3
0.00012207 3
3.00012</
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.
<
import java.util.LinkedList;
Line 2,620:
}
}
</syntaxhighlight>
{{out}}
<pre>Input Operation Stack after
Line 2,639:
=={{header|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>
{{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.)
<
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 ^ ^ / +")</
{{out}}
<pre>3: 3
Line 2,719:
=={{header|Kotlin}}==
<
fun rpnCalculate(expr: String) {
Line 2,758:
val expr = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
rpnCalculate(expr)
}</
{{out}}
Line 2,783:
==[[header|Lambdatalk]]==
<syntaxhighlight 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>
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
global stack$
Line 2,952:
stack$=mid$(stack$,instr(stack$,"|")+1)
end function
</syntaxhighlight>
{{out}}
Line 2,978:
=={{header|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 *" )</
{{out}}
<pre>
Line 3,058:
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Rpn_Calc {
Rem Form 80,60
Line 3,095:
}
Rpn_Calc
</syntaxhighlight>
{{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".)
<
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 ^ ^ / +"]];</
{{out}}
<pre>3: 3
Line 3,199:
=={{header|Maxima}}==
<
rpow(x, y) := y^x$
Line 3,237:
)$
rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +"), numer;</
===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</
=={{header|MiniScript}}==
<
tokens = inputText.split
stack = []
Line 3,278:
end function
print RPN("3 4 2 * 1 5 - 2 3 ^ ^ / +")</
{{out}}
Line 3,301:
{{works with|GNU TROFF|1.22.2}}
<
RPN parser implementation in TROFF
Line 3,414:
.el .RPNPRINT
..
.RPNPARSE 3 4 2 * 1 5 - 2 3 ^ ^ / + \" Our input expression</
====Output====
<syntaxhighlight lang="text"> 3
3 4
3 4 2
Line 3,430:
3 0
3
3</
===Modern version===
Line 3,437:
{{works with|GNU Troff|1.22.2}}
<
===========================
Array implementation
Line 3,525:
..
.rpn 3 4 2 * 1 5 - 2 3 ^ ^ / +
.stack.dump</
====Output====
<syntaxhighlight lang="text">3
3 4
3 4 2
Line 3,541:
3 0
3
3</
=={{header|NetRexx}}==
{{trans|Java}}
<
options replace format comments java crossref symbols nobinary
Line 3,633:
calc = stack.toString
return calc
</syntaxhighlight>
{{out}}
Line 3,657:
=={{header|Nim}}==
{{trans|Python}}
<
type Stack = seq[float]
Line 3,726:
for i, y in x:
stdout.write y.alignLeft(maxColWidths[i])
echo ""</
{{out}}
Line 3,746:
=={{header|Objeck}}==
<
use IO;
use Struct;
Line 3,810:
}
}
</syntaxhighlight>
{{out}}
Line 3,832:
=={{header|OCaml}}==
<
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</
Evaluation of the test expression:
Line 3,884:
Oforth uses RPN and natively parse RPN.
<
{{out}}
Line 3,893:
To show the changes in the stack, we can use .l after evaluating each word :
<
rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +")</
{{out}}
Line 3,915:
=={{header|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</
{{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.
<
epush(x) = {
Line 4,002:
};
parseRPN([3, 4, 2, "*", 1, 5, "-", 2, 3, "^", "^", "/", "+"]); \\ Our input expression</
===Output===
<syntaxhighlight lang="text">[3]
[3, 4]
[3, 4, 2]
Line 4,017:
[3, 8, 65536]
[3, 1/8192]
[24577/8192]</
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}}==
<
use warnings;
use feature 'say';
Line 4,048:
say $a;
eval $a;
}</
{{out}}
<pre>(4)*(2)
Line 4,059:
=={{header|Phix}}==
<!--<
<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>
<!--</
{{out}}
<pre>
Line 4,097:
=={{header|PHP}}==
<
<?php
function rpn($postFix){
Line 4,143:
echo "Compute Value: " . rpn("3 4 2 * 1 5 - 2 3 ^ ^ / + ");
?>
</syntaxhighlight>
{{out}}
<pre>
Line 4,165:
=={{header|PicoLisp}}==
This is an integer-only calculator:
<
(let (^ ** Stack) # Define '^' from the built-in '**'
(prinl "Token Stack")
Line 4,176:
(space 6)
(println Stack) )
(println (car Stack)) ) )</
Test (note that the top-of-stack is in the left-most position):
<
Token Stack
3 (3)
Line 4,194:
+ (3)
3
-> 3</
=={{header|PL/I}}==
<
declare expression character (100) varying initial ('');
declare ch character (1);
Line 4,228:
put skip list ('The evaluated expression = ' || stack);
end Calculator;</
<pre>
Stack contents:
Line 4,256:
=={{header|PL/SQL}}==
<
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;
/</
Testing:
<
dbms_output.put_line(chr(10) || 'Result: ' || rpn_calc('3 4 2 * 1 5 - 2 3 ^ ^ / +'));
end;
/</
Output:
Line 4,334:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function Invoke-Rpn
{
Line 4,467:
Invoke-Rpn -Expression "3 4 2 * 1 5 - 2 3 ^ ^ / +" -DisplayState
</syntaxhighlight>
{{Out}}
Line 4,491:
=={{header|Prolog}}==
Works with SWI-Prolog.
<
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.</
{{out}}
<pre>5 ?- rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +").
Line 4,560:
=={{header|Python}}==
=== Version 1 ===
<
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])</
{{out}}
Line 4,642:
=== Version 2 ===
<
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</
{{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">
[ stack ] is switch.arg ( --> [ )
Line 4,710:
$ "3 4 2 * 1 5 - 2 3 ^ ^ / +" rpncalc
say "Result: " echo</
{{out}}
Line 4,731:
=={{header|Racket}}==
<
#lang racket
Line 4,747:
(reverse (cons x s)))])))
</syntaxhighlight>
Test case
<pre>
Line 4,768:
Reading from a string:
<
(calculate-RPN (in-port read (open-input-string "3.0 4 2 * 1 5 - 2 3 ^ ^ / +")))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-25}}
<syntaxhighlight lang="raku" line>
my $proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +';
Line 4,798:
RPN.new.run($proggie);
</syntaxhighlight>
{{out}}
<pre>3 ()
Line 4,817:
=={{header|REXX}}==
===version 1===
<
* 09.11.2012 Walter Pachl translates from PL/I
**********************************************************************/
Line 4,869:
End
Say ol
Return</
{{out}}
<pre>
Line 4,888:
:::: <big><big> 3.0 .4e1 2e0 * +1. 5 - 2 3 ** ** / + </big></big>
which is the essentially the same as the default used by the REXX program.
<
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</
'''output''' when using the default input:
<pre>
Line 4,951:
::* allows remainder division <big>//</big>
::* allows concatenation <big>||</big>
<
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</
'''output''' is identical to the 2<sup>nd</sup> REXX version.
<br><br>
Line 4,999:
=={{header|Ruby}}==
See [[Parsing/RPN/Ruby]]
<
value = rpn.eval</
{{out}}
<pre>for RPN expression: 3 4 2 * 1 5 - 2 3 ^ ^ / +
Line 5,020:
=={{header|Run BASIC}}==
<
j = 0
Line 5,053:
if op$ = "+" then op = a + b
if op$ = "-" then op = a - b
end function</
<pre>Push Num 3 to stack: 3
Push Num 4 to stack: 3 4
Line 5,069:
=={{header|Rust}}==
<
let tokens = text.split_whitespace();
let mut stack: Vec<f64> = vec![];
Line 5,122:
println!("\nresult: {}", rpn(text));
}</
{{out}}
<pre>input operation stack
Line 5,143:
=={{header|Scala}}==
<
val PRINT_STACK_CONTENTS: Boolean = true
Line 5,182:
}
}
}</
{{out}}
<pre>
Line 5,202:
=={{header|Sidef}}==
{{trans|Raku}}
<
class RPN(arr=[]) {
Line 5,234:
}
RPN.new.run(proggie)</
{{out}}
<pre>
Line 5,260:
No attempt is made to check for invalid syntax, stack overflow or underflow, etc.
<
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</
{{in}}
<pre>3 4 2 * 1 5 - 2 3 ** ** / +</pre>
Line 5,307:
=={{header|Swift}}==
{{trans|Go}}
<
"^": (prec: 4, rAssoc: true),
"*": (prec: 3, rAssoc: false),
Line 5,364:
input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
"infix: \(input)"
"postfix: \(parseInfix(input))"</
{{out}}
<pre>"postfix: 3 4 2 * 1 5 - 2 3 ^ ^ / +"</pre>
=={{header|Tcl}}==
<
proc pop stk {
upvar 1 $stk s
Line 5,417:
}
puts [evaluate {3 4 2 * 1 5 - 2 3 ^ ^ / +}]</
{{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.
<
exp() {
Line 5,505:
}
rpn 3 4 2 '*' 1 5 '-' 2 3 '^' '^' '/' '+'</
===Output===
<syntaxhighlight lang="text">3 : 3
4 : 3 4
2 : 3 4 2
Line 5,521:
/ : 3 0
+ : 3
3</
=={{header|VBA}}==
Line 5,527:
{{trans|Liberty BASIC}}
<
Function RPN(expr$)
Line 5,612:
pop$ = Split(stack$, "|")(0)
stack$ = Mid$(stack$, InStr(stack$, "|") + 1)
End Function</
{{out}}
Line 5,638:
{{trans|C}}
Updated to Vlang version 0.2.2
<
const (
Line 5,727:
println('\nResult: $result')
}
</syntaxhighlight>
{{out}}
<pre>Input: 3 4 2 * 1 5 - 2 3 ^ ^ / +
Line 5,750:
{{trans|Kotlin}}
{{libheader|Wren-seq}}
<
var rpnCalculate = Fn.new { |expr|
Line 5,781:
var expr = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
rpnCalculate.call(expr)</
{{out}}
Line 5,809:
{{trans|VBA}}
<syntaxhighlight lang="xojo">
Function RPN(expr As String) As String
Line 5,866:
Return stack(2)
End Function</
Line 5,893:
=={{header|zkl}}==
<
fcn parseRPN(e){
Line 5,910:
}
println("result: ", stack[0])
}</
<
foreach t in (tests) { parseRPN(t) }</
{{out}}
<pre>
|