An interactive reverse polish calculator. This tiny project is an extension of the example given in chapter 4 of the book "The C Programming Language" second edition, by Brian W. Kernighan and Dennis M. Ritchie (ISBN: 978-93-325-4944-9). Basically exersice 4.3 t0 4.9.
The Makefile here is taken from simple-make-build.
To build this project just call make
, the makefile handles the rest.
# clone repo
git clone --depth=1 https://github.com/SidhBhat/reverse-polish-calculator
# build
make
# and execute...
./build/reverse-polish-calculator
The moment you run the progran you are presented with a interactive prompt, where you can type your calculations. The expressions you type here are in the reverse polish syntax.
Every expression consists a function and it's arguments in order to the left of the function.
the function can return only one value, which is the value of the expression. Suppose the function
is func
with arguments a
, b
and c
, we would write:
a b c func
we can pass this value to a another function func2
with two arguments as:
arg1 a b c func func 2
Here we notice a b c func
is bahaving as a single agrument to func2
.
Thus a b c - +
and a b + c -
. Let us take a more
complicated expression a sin 2 ^ b cos ^ 4 +
. Let us see
one more example
2 x * 3 + cos e x ^ * y ln +
The reverse polish syntax is easy to implement in code as it is independant of operator precedance, but is pretty unintutive to the human reader.
sin
cos
tan
sinh
cosh
tanh
pow
ln
log
sqrt
cbrt
+
-
*
/
%
^
These are commands that take zero arguments but allow one to modify the program environment:
# Get the last answer
ans
# clear the stack memory
clear
# exit the program
exit
?
Operator returns the value of the last calculation, so for example 2 3 * ? +
would be
equal to
=
The assignment operator assigns a variable to the value of the second argument. A variable must be the first argument.
If that is not the case an error is thrown. The value of the expression is equal to the assignment value that is, the
second argument. We can use this fact to perform assignments (multiple in a single expression) along with computations.
a 1 sin 2 ^ = b 1 cos 2 ^ = +
would evalute to a b +
now we would again
get
We have 26 variables which can hold values. These are the english small alphabets. We can assign values to these variables
using the =
operator.
The branch beta
is used for devlopment purposes. When you build here the program prints the stack along with the answer.
This is used for debugging purpose. If you use this branch please make sure to remove the relevant lines when merging into
main.
As with my other projects you can start contributing by simply creating a pull request. And for suggesions you can contact me by email1.
Footnotes
-
available on my profile ↩