Calculators

What does a calculator do? Is this everything?

Four-function Calculators: UI is hell

See lcamtuf.substack.com/p/ui-is-hell-four-function-calculators.

gnome-calculator on my laptop is a plausible implementation of this, but note that they added some things.

A well-behaved case: pressing 1 + 2 * 3 =. This evaluates ((1+2)*3) and returns 9

What happens if the presses are 1 + 2 = 9? After the =, the display shows 3. Pressing the 9 doesn't lead to 39. We need an "input reset" flag.

But that flag doesn't apply to operators pressed after a press of =; that just should go on with the calculation: 1 + 2 = * 3

What about pressing 2 + * 3? Two operators in a row are most likely an error. Unless, maybe, that * was a minus sign.

When migrating a calculator to a computer with a full graphical interface, it makes sense to rethink this entire keypress-at-a-time interface, and allow backspacing and/or full line display until a calculation is required.

Parenthesized Expression Evaluation

Recursive-descent parsing of arithmetical expressions is the simplest, though there are non-recursive (stack-based) strategies.

Parsing code used in Comp 271 should be in pld.cs.luc.edu/courses/271/spr18/demos/expressionsij.zip (my code is in ~/271/expressions; see especially expr_eval.java)

    java expr_eval     (traced version is expr_exp)

    java expr_assign

Notes on this strategy: pld.cs.luc.edu/courses/271/spr18/mnotes/recursion.html#exprtrees

Demo of command-line expressions and recursive-descent parsing

With a calculator interface instead of a command-line interface, some things have to be modified appropriately. Generally, the '(' key clears the display and starts a new subexpression. Operator keys might display the current operator on the screen. The ')' key acts a bit like the '=' key for the current subexpression, displaying the results so far. galculator takes this approach. If that subexpression was involved in a pending operation, as in 3 * ( 4 + 1 ), pressing ) displays 5, and then pressing = displays 15.

To put it another way, we might use states such as the following (probably not a complete list):

In NUMBER_ENTRY state, additional digits pressed go into the display. The first number pressed clears the display.

SUBEXPRESSION state is a lot like NUMBER_ENTRY state, except that we remember we're in a subexpression. We enter it when a left parenthesis is pressed.

We go into OPERATOR state when an operator key is pressed. We save and clear the display, and save the operator. If a digit is pressed in OPERATOR state, we go into NUMBER_ENTRY state again.

We go into EQUALS state when the "=" key is pressed, or a ). We retrieve the last stored operator and apply it to the previously saved display and the current display. The display is updated to show the result.

The other alternative is to display the entire expression on the display line. qalculate does this.