RpnCalc
RpnCalc is a small calculator program I wrote in euphoria that handles RPN (reverse polish notation) input. The output of the program is pretty poorly designed. I will design and implement a better one soon hopefully. Anyways, here's the code that I wrote:
{{{include get.e
procedure main() sequence stack integer key,input,switch input=0 switch=0 key=0 stack={}
while key!='q' do key=wait_key() if key>47 and key<58 then
- if switch=0 then
- input=key-48 switch=1
- input=input*10+(key-48)
else
- --Explicit push command if key=13 then
stack=input&stack switch=0
- exit
- --Push input onto stack if there's new input if switch=1 then
stack=input&stack
if length(stack)>1 then
- --Begin commands block if key='+' then
- stack[2]=stack[2]+stack[1]
- stack[2]=stack[2]-stack[1]
- stack[2]=stack[2]*stack[1]
- stack[2]=stack[2]/stack[1]
- stack[2]=power(stack[2],stack[1])
- stack[2]=remainder(stack[2],stack[1])
- puts(1,"Error: Stack Underflow\n") key='q'
end if end while end procedure
main() }}}
Comments on the code are welcome. I may port the program to some other programming language (I'd really like this for my TI calculator). The program would most likely be MUCH prettier in a lisp or forth type language, but, this was an overnight hack in euphoria, so, that's what it looks like.
Comments
An RPN calculator named RPN83 is already available for the TI-83 calculator, and most HPs support RPN by default. The webpage for RPN83 is at http://patrick.wattle.id.au/cameron/software/ti83/rpn/
I wrote a version in Python, which may be removed if anyone thinks it is just unnecessarily taking up page space!:
1 import sys
2
3 def isOp(c):
4 return c in ['+', '-', '*', '/']
5
6 def binOp(a,b,o):
7 if o=='+': return a+b
8 elif o=='-': return a-b
9 elif o=='*': return a*b
10 elif o=='/':
11 try:
12 return a/b
13 except ZeroDivisionError:
14 print "Can't divide by zero!"
15 sys.exit()
16
17 def evalRPN(expr):
18 stack = []
19 for elem in expr:
20 if isOp(elem):
21 op = elem
22 b = stack.pop()
23 a = stack.pop()
24 stack.append(binOp(a,b,op))
25 else:
26 stack.append(int(elem))
27 return stack.pop()
28
29
30 # Infinite REPL
31 while True:
32 expression = raw_input(">> ").split(" ")
33 print evalRPN(expression)
-- MikeNolan
