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 =
12A0 = null
B = 12+A0 = {12,+}
B = <empty>5A0 = {12,+}
B = 5=A0 = null
B = 17
5 * ( 1 + 1 ) =
5A0 = null
B = 5*A0 = {5, *}
B = <empty>(A0 = {5, *}
A1 = null
B = <empty>1A0 = {5, *}
A1 = null
B = 1;+A0 = {5, *}
A1 = {1, +}
B = <empty>1A0 = {5, *}
A1 = {1, +}
B = 1;)A0 = {5, *}
B = 2;=A0 = null
B = 10;
Thoughts? Potential bugs?
That seems fancy and confusing and hard to come up with? It reminds me of trying to code an expression evaluator and giving up; my brain is full of all these symbol stacks that I’m never sure are stacked up right.
You could duplicate the functionality of most handheld calculators, where when you press equals multiple times it repeats the last operation multiple times, by changing the functionality of equals. Instead of setting A_0 = null it would set A_0 = {B,A_0[1]} — but it wouldn’t work with subtraction and division =(
I dunno what that’s called. Maybe an event stack? You are sort of walking a tree in some kind of left-branch-first manner. I don’t know algorithm names =O