At first I was all how am i going to deal with the order of operations? and I thought about maybe creating a parse tree. That seemed excessive, especially when I thought about how simple calculators usually work (from a usage standpoint). Which was okay, even good, but how to account for brackets. Or better, nested brackets?
There’s probably a real name for this method, but I don’t know it. Karl will definitely know? And if he doesn’t he’s lying.
So we have the screen, which I will call B and a stack of registers which I will call An. Each register has a value and an operator.
What happens usually is you type a bunch of literals, and then an operator. When you type an operator it checks if there is data in the nearest register, and if so combines the two values using the operator stored in the register and moves the new value and operator into the register. There are only binary operators at the moment, but unary operators would be easy to implement.
When you open a bracket, a new register is pushed onto the stack and the system makes use of that one from now on. When you close a bracket, the operation of the last register is performed with B, and the last register is popped off the stack – its value stored in B.
In this way the calculator supports nested brackets.
12 + 5 =
12
A0 = null
B = 12
+
A0 = {12,+}
B = <empty>
5
A0 = {12,+}
B = 5
=
A0 = null
B = 17
5 * ( 1 + 1 ) =
5
A0 = null
B = 5
*
A0 = {5, *}
B = <empty>
(
A0 = {5, *}
A1 = null
B = <empty>
1
A0 = {5, *}
A1 = null
B = 1;
+
A0 = {5, *}
A1 = {1, +}
B = <empty>
1
A0 = {5, *}
A1 = {1, +}
B = 1;
)
A0 = {5, *}
B = 2;
=
A0 = null
B = 10;
Thoughts? Potential bugs?