https://github.com/howardabrams/rpn-calc
A streaming calculator that computes in reverse polish notation.
https://github.com/howardabrams/rpn-calc
Last synced: 2 months ago
JSON representation
A streaming calculator that computes in reverse polish notation.
- Host: GitHub
- URL: https://github.com/howardabrams/rpn-calc
- Owner: howardabrams
- License: epl-1.0
- Created: 2016-06-01T03:09:12.000Z (about 10 years ago)
- Default Branch: master
- Last Pushed: 2016-06-01T03:49:12.000Z (about 10 years ago)
- Last Synced: 2025-12-26T09:34:12.076Z (6 months ago)
- Language: Clojure
- Size: 9.77 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.org
- License: LICENSE
Awesome Lists containing this project
README
#+TITLE: RPN Calculator
#+AUTHOR: Howard Abrams
#+EMAIL: howard.abrams@gmail.com
#+DATE: 2016 May 15
The project answers a programming problem in [[https://gist.github.com/ckolbeck/33760242f760f6d82658][this gist]] about making a
stream calculator that calculates in reverse polish notation. While the
gist request Java, the introduction I received mentioned any language.
I hoped using Clojure would require a shorter amount of code, and a
result that was easier to read.
* Homework Problem
Write a reverse polish notation calculator in Java. Your calculator
should take a RPN statements composed of space separated integers
and operators (see below) on a single line from stdin and perform
the requested operation. In the event of unparseable input your
program should print a sane error message to stderr and continue. If
the result of a calculation is not a single integer your program
should print the current state of the stack. You should include unit
and functional tests. Please don't spend more than 2-3 hours on
this.
Operators:
+
integer addition
-
integer subtraction
*
integer multiplication
/
integer quotient
%
integer modulus
p
print: remove and print the top value on the stack
d
duplicate the value on the top of the stack
* Example Session
#+BEGIN_EXAMPLE
6 7 +
13
4 -2 * 2 *
-16
2 3 4 + d p *
7
14
2 8 2 +
2 10
2 +
Error: insufficient input for '+' operator
2 2 r
Error: Couldn't parse 'r' as an integer or operator
2.5 3 +
Error: Couldn't parse '2.5' as an integer or operator
#+END_EXAMPLE
* Extra Credit
Instead of taking a line at a time, accept a stream of integers and
operators on stdin, one per line. If a line is unparseable or would
put the stack into a bad state, print an error message, drop the bad
input, and continue on. If the program exits due to an EOF, print
the current state of the stack before exiting.
* Final Thoughts
The original project required that the calculations only work with
Integers, so I simply called out to Clojure's built-in =read-string=
which the REPL uses to convert a =String= to other Clojure primitives,
like =Integer=, symbols, Floats, etc.
While the parser/tokenizer may create a =Float=, I ignore these during
the process phase.