« Washing My Keyboard | Main | Hacking on the PowerShell RPN Calculator »

October 15, 2007

RPN Calculator in PowerShell

I was auditing a course that we teach and one assignment was to work on an RPN calculator. The instructions say that you CANNOT use the .Net Stack class, which makes sense because then the problem becomes too easy. But then I got to thinking and realized that if I DID use the Stack class, it would be pretty simple to make an RPN calculator in PowerShell. So I did, while sitting in the back of class, in about 10 minutes:

$s = new-object System.Collections.Stack 
$n = 0 
foreach ($a in $args) { 
    switch -regex ($a) { 
        "[+-\/\*^]" { $t = $s.Pop() } 
    switch ($a) { 
        "+" { $s.Push($s.Pop() + $t) } 
        "-" { $s.Push($s.Pop() - $t) } 
        "*" { $s.Push($s.Pop() * $t) } 
        "/" { $s.Push($s.Pop() / $t) } 
        "^" { $s.Push([System.Math]::Pow($s.Pop(),$t)) } 
        "e" { $s.Push([System.Math]::E) } 
        "pi" { $s.Push([System.Math]::PI) } 
        "sqrt" { $s.Push([System.Math]::Sqrt($s.Pop())) } 
        { [System.Int32]::TryParse($a,[ref]$n) } { $s.Push($n) } 

You can do cute things like (assuming it is called rpn.ps1):

./rpn 3 2 ^ 4 2 ^ + sqrt

And of course you can extend it to add new functionality in a trivial and obvious way; the Math class includes absolute value, log, and the trigonometric functions. I guess it needs a dup function also, which you could easily do by calling Pop() on $s.Peek().

Posted by AdamBa at October 15, 2007 06:28 PM

Trackback Pings

TrackBack URL for this entry:


1. I wonder if this could be programmed in 4NT (which I currently use).

2. There is a really nice RPN calculator called CoCalc. It comes as a html file with an associated file call cocalc.class. I believe it is all done in Java.

3. RPN calculators seem to have disappeared except at the high end. I would love to have a $20 calculator I could carry in my backpack, but they seem not to exist. I find algebraic entry machines considerably harder to use, since I have to decide beforehand exactly what I am going to do, while with an RPN machine I can make it up as I go along.

Posted by: Marble Chair at October 16, 2007 04:11 PM