layout: post
title: “Calculator Walkthrough: Part 4”
description: “Designing using a state machine”
categories: [“Worked Examples”]
seriesId: “Annotated walkthroughs”

seriesOrder: 4

In this series of posts, I’ve been developing a simple pocket calculator app.

In the first post, we completed a first draft of the design, using type-first development.
and in the second post, we created an initial implemeentation.

In the previous post, we created the rest of the code, including the user interface, and attempted to use it.

But the final result was unusable! The problem wasn’t that the code was buggy, it was that I didn’t
spend enough time thinking about the requirements before I started coding!

Oh well. As Fred Brooks famously said: “plan to throw one away; you will, anyhow” (although that is a bit simplistic).

The good news is that I have learned from the previous bad implementation, and have a plan to make the design better.

Reviewing the bad design

Looking at the design and implementation (see this gist), a few things stand out:

First, the event handling types such as UpdateDisplayFromDigit did not take into account the context, the current state of the calculator.
The allowAppend flag we added as a patch was one way to take the context into account, but it smells awful bad.

Second there was a bit of special case code for certain inputs (Zero and DecimalSeparator), as you can see from this code snippet:

  1. let appendCh=
  2. match digit with
  3. | Zero ->
  4. // only allow one 0 at start of display
  5. if display="0" then "" else "0"
  6. | One -> "1"
  7. | // snip
  8. | DecimalSeparator ->
  9. if display="" then
  10. // handle empty display with special case
  11. "0" + config.decimalSeparator
  12. else if display.Contains(config.decimalSeparator) then
  13. // don't allow two decimal separators
  14. ""
  15. else
  16. config.decimalSeparator

This makes me think that these inputs should be treated as different in the design itself and not hidden in the implementation
— after all we want the design to also act as documentation as much as possible.

Using a finite state machine as a design tool

So if the ad-hoc, make-it-up-as-you-go-along approach failed, what should I do instead?

Well, I am a big proponent of using finite state machines
(“FSMs” — not be confused with the True FSM) where appropriate.
It is amazing how often a program can be modelled as a state machine.

What are the benefits of using state machines? I’m going to repeat what I said in another post.

Each state can have different allowable behavior.
In other words, a state machine forces you to think about context, and what options are available in that context.

In this case, I forgot that the context changed after an Add was processed, and thus the rules for accumulating digits changed too.

All the states are explicitly documented.
It is all too easy to have important states that are implicit but never documented.

For example, I have created special code to deal with zero and decimal separators. Currently it is buried away in the implementation, but it should be part of the design.

It is a design tool that forces you to think about every possibility that could occur.
A common cause of errors is that certain edge cases are not handled, but a state machine forces all cases to be thought about.

In this case, in addition to the most obvious bug, there are still some edge cases that are not dealt with properly,
such as immediately following a math operation with another math operation. What should happen then?

How to implement simple finite state machines in F#

You are probably familiar with complex FSMs, such as those used in language parsers and regular expressions.
Those kinds of state machines are generated from rule sets or grammars, and are quite complicated.

The kinds of state machines that I’m talking about are much, much simpler.
Just a few cases at the most, with a small number of transitions, so we don’t need to use complex generators.

Here’s an example of what I am talking about:
State machine

So what is the best way to implement these simple state machines in F#?

Now, designing and implementing FSMs is a complex topic in in own right, with
its own terminology (NFAs and DFAs, Moore vs. Mealy, etc),
and whole businesses built around it.

In F#, there are a number of possible approaches, such as table driven, or mutually recursive functions, or agents, or OO-style subclasses, etc.

But my preferred approach (for an ad-hoc manual implementation) makes extensive use of union types and pattern matching.

First, create a union type that represents all the states.
For example, if there are three states called “A”, “B” and “C”, the type would look like this:

  1. type State =
  2. | AState
  3. | BState
  4. | CState

In many cases, each state will need to store some data that is relevant to that state.
So we will need to create types to hold that data as well.

  1. type State =
  2. | AState of AStateData
  3. | BState of BStateData
  4. | CState
  5. and AStateData =
  6. {something:int}
  7. and BStateData =
  8. {somethingElse:int}

Next, all possible events that can happen are defined in another union type. If events have data associated with them, add that as well.

  1. type InputEvent =
  2. | XEvent
  3. | YEvent of YEventData
  4. | ZEvent
  5. and YEventData =
  6. {eventData:string}

Finally, we can create a “transition” function that, given a current state and input event, returns a new state.

  1. let transition (currentState,inputEvent) =
  2. match currentState,inputEvent with
  3. | AState, XEvent -> // new state
  4. | AState, YEvent -> // new state
  5. | AState, ZEvent -> // new state
  6. | BState, XEvent -> // new state
  7. | BState, YEvent -> // new state
  8. | CState, XEvent -> // new state
  9. | CState, ZEvent -> // new state

What I like about this approach in a language with pattern matching, like F#,
is that if we forget to handle a particular combination of state and event, we get a compiler warning. How awesome is that?

It’s true that, for systems with many states and input events, it may be unreasonable to expect every possible combination to be explicitly handled.
But in my experience, many nasty bugs are caused by processing an event when you shouldn’t, exactly as we saw with the original design accumulating digits when it shouldn’t have.

Forcing yourself to consider every possible combination is thus a helpful design practice.

Now, even with a small number of states and events, the number of possible combinations gets large very quickly.
To make it more manageable in practice, I typically create a series of helper functions, one for each state, like this:

  1. let aStateHandler stateData inputEvent =
  2. match inputEvent with
  3. | XEvent -> // new state
  4. | YEvent _ -> // new state
  5. | ZEvent -> // new state
  6. let bStateHandler stateData inputEvent =
  7. match inputEvent with
  8. | XEvent -> // new state
  9. | YEvent _ -> // new state
  10. | ZEvent -> // new state
  11. let cStateHandler inputEvent =
  12. match inputEvent with
  13. | XEvent -> // new state
  14. | YEvent _ -> // new state
  15. | ZEvent -> // new state
  16. let transition (currentState,inputEvent) =
  17. match currentState with
  18. | AState stateData ->
  19. // new state
  20. aStateHandler stateData inputEvent
  21. | BState stateData ->
  22. // new state
  23. bStateHandler stateData inputEvent
  24. | CState ->
  25. // new state
  26. cStateHandler inputEvent

So let’s try this approach and attempt to implement the state diagram above:

  1. let aStateHandler stateData inputEvent =
  2. match inputEvent with
  3. | XEvent ->
  4. // transition to B state
  5. BState {somethingElse=stateData.something}
  6. | YEvent _ ->
  7. // stay in A state
  8. AState stateData
  9. | ZEvent ->
  10. // transition to C state
  11. CState
  12. let bStateHandler stateData inputEvent =
  13. match inputEvent with
  14. | XEvent ->
  15. // stay in B state
  16. BState stateData
  17. | YEvent _ ->
  18. // transition to C state
  19. CState
  20. let cStateHandler inputEvent =
  21. match inputEvent with
  22. | XEvent ->
  23. // stay in C state
  24. CState
  25. | ZEvent ->
  26. // transition to B state
  27. BState {somethingElse=42}
  28. let transition (currentState,inputEvent) =
  29. match currentState with
  30. | AState stateData ->
  31. aStateHandler stateData inputEvent
  32. | BState stateData ->
  33. bStateHandler stateData inputEvent
  34. | CState ->
  35. cStateHandler inputEvent

If we try to compile this, we immediately get some warnings:

  • (near bStateHandler) Incomplete pattern matches on this expression. For example, the value 'ZEvent' may indicate a case not covered by the pattern(s).
  • (near cStateHandler) Incomplete pattern matches on this expression. For example, the value 'YEvent (_)' may indicate a case not covered by the pattern(s).

This is really helpful. It means we have missed some edge cases and we should change our code to handle these events.

By the way, please do not fix the code with a wildcard match (underscore)! That defeats the purpose.
If you want to ignore an event, do it explicitly.

Here’s the fixed up code, which compiles without warnings:

  1. let bStateHandler stateData inputEvent =
  2. match inputEvent with
  3. | XEvent
  4. | ZEvent ->
  5. // stay in B state
  6. BState stateData
  7. | YEvent _ ->
  8. // transition to C state
  9. CState
  10. let cStateHandler inputEvent =
  11. match inputEvent with
  12. | XEvent
  13. | YEvent _ ->
  14. // stay in C state
  15. CState
  16. | ZEvent ->
  17. // transition to B state
  18. BState {somethingElse=42}

You can see the code for this example in this gist.

Designing the state machine for the calculator

Let’s sketch out a state machine for the calculator now. Here’s a first attempt:

Calculator state machine v1

Each state is a box, and the events that trigger transitions (such as a digit or math operation or Equals) are in red.

If we follow through a sequence of events for something like 1 Add 2 Equals, you can see that we’ll end up at the “Show result” state at the bottom.

But remember that we wanted to raise the handling of zero and decimal separators up to the design level?

So let’s create special events for those inputs, and a new state “accumulate with decimal” that ignores subsequent decimal separators.

Here’s version 2:

Calculator state machine v1

Finalizing the state machine

“Good artists copy. Great artists steal.”
— Pablo Picasso (but not really)

At this point, I’m thinking that surely I can’t be only person to have thought of using a state machine to model a calculator?
Perhaps I can do some research and steal borrow someone else’s design?

Sure enough, googling for “calculator state machine” brings up all sorts of results, including @2/Finite_State_Machines_and_the_">this one
which has a detailed spec and state transition diagram.

Looking at that diagram, and doing some more thinking, leads to the following insights:

  • The “clear” state and zero state are the same. Sometimes there is a pending op, sometimes not.
  • A math operation and Equals are very similar in that they update the display with any pending calculation.
    The only difference is whether a pending op is added to the state or not.
  • The error message case definitely needs to be a distinct state. It ignores all input other than Clear.

With these insights in mind then, here’s version 3 of our state transition diagram:

Calculator state machine v1

I’m only showing the key transitions — it would be too overwhelming to show all of them.
But it does give us enough information to get started on the detailed requirements.

As we can see, there are five states:

  • ZeroState
  • AccumulatorState
  • AccumulatorDecimalState
  • ComputedState
  • ErrorState

And there are six possible inputs:

  • Zero
  • NonZeroDigit
  • DecimalSeparator
  • MathOp
  • Equals
  • Clear

Let’s document each state, and what data it needs to store, if any.







































StateData associated with stateSpecial behavior?
ZeroState(optional) pending opIgnores all Zero input
AccumulatorStatebuffer and (optional) pending opAccumulates digits in buffer
AccumulatorDecimalStatebuffer and (optional) pending opAccumulates digits in buffer, but ignores decimal separators
ComputedStateCalculated number and (optional) pending op
ErrorStateError messageIgnores all input other than Clear

Documenting each state and event combination

Next we should think about what happens for each state and event combination.
As with the sample code above, we’ll group them so that we only have to deal with the events for one state at a time.

Let’s start with the ZeroState state. Here are the transitions for each type of input:













































InputActionNew State
Zero(ignore)ZeroState
NonZeroDigitStart a new accumulator with the digit.AccumulatorState
DecimalSeparatorStart a new accumulator with “0.”AccumulatorDecimalState
MathOpGo to Computed or ErrorState state.

If there is a pending op, update the display based on the result of the calculation (or error).

Also, if calculation was successful, push a new pending op, built from the event, using a current number of “0”.
ComputedState
EqualsAs with MathOp, but without any pending opComputedState
Clear(ignore)ZeroState

We can repeat the process with the AccumulatorState state. Here are the transitions for each type of input:














































InputActionNew State
ZeroAppend “0” to the buffer.AccumulatorState
NonZeroDigitAppend the digit to the buffer.AccumulatorState
DecimalSeparatorAppend the separator to the buffer, and transition to new state.AccumulatorDecimalState
MathOpGo to Computed or ErrorState state.

If there is a pending op, update the display based on the result of the calculation (or error).

Also, if calculation was successful, push a new pending op, built from the event, using a current number based on whatever is in the accumulator.
ComputedState
EqualsAs with MathOp, but without any pending opComputedState
ClearGo to Zero state. Clear any pending op.ZeroState

The event handling for AccumulatorDecimalState state is the same, except that DecimalSeparator is ignored.

What about the ComputedState state. Here are the transitions for each type of input:













































InputActionNew State
ZeroGo to ZeroState state, but preserve any pending opZeroState
NonZeroDigitStart a new accumulator, preserving any pending opAccumulatorState
DecimalSeparatorStart a new decimal accumulator, preserving any pending opAccumulatorDecimalState
MathOpStay in Computed state. Replace any pending op with a new one built from the input eventComputedState
EqualsStay in Computed state. Clear any pending opComputedState
ClearGo to Zero state. Clear any pending op.ZeroState

Finally, the ErrorState state is very easy. :





















InputActionNew State
Zero, NonZeroDigit, DecimalSeparator
MathOp, Equals
(ignore)ErrorState
ClearGo to Zero state. Clear any pending op.ZeroState

Converting the states into F# code

Now that we’ve done all this work, the conversion into types is straightforward.

Here are the main types:

  1. type Calculate = CalculatorInput * CalculatorState -> CalculatorState
  2. // five states
  3. and CalculatorState =
  4. | ZeroState of ZeroStateData
  5. | AccumulatorState of AccumulatorStateData
  6. | AccumulatorWithDecimalState of AccumulatorStateData
  7. | ComputedState of ComputedStateData
  8. | ErrorState of ErrorStateData
  9. // six inputs
  10. and CalculatorInput =
  11. | Zero
  12. | Digit of NonZeroDigit
  13. | DecimalSeparator
  14. | MathOp of CalculatorMathOp
  15. | Equals
  16. | Clear
  17. // data associated with each state
  18. and ZeroStateData =
  19. PendingOp option
  20. and AccumulatorStateData =
  21. {digits:DigitAccumulator; pendingOp:PendingOp option}
  22. and ComputedStateData =
  23. {displayNumber:Number; pendingOp:PendingOp option}
  24. and ErrorStateData =
  25. MathOperationError

If we compare these types to the first design (below), we have now made it clear that there is something special about Zero and DecimalSeparator,
as they have been promoted to first class citizens of the input type.

  1. // from the old design
  2. type CalculatorInput =
  3. | Digit of CalculatorDigit
  4. | Op of CalculatorMathOp
  5. | Action of CalculatorAction
  6. // from the new design
  7. type CalculatorInput =
  8. | Zero
  9. | Digit of NonZeroDigit
  10. | DecimalSeparator
  11. | MathOp of CalculatorMathOp
  12. | Equals
  13. | Clear

Also, in the old design, we had a single state type (below) that stored data for all contexts, while in the new design, the state is explicitly different for each context.
The types ZeroStateData, AccumulatorStateData, ComputedStateData, and ErrorStateData make this obvious.

  1. // from the old design
  2. type CalculatorState = {
  3. display: CalculatorDisplay
  4. pendingOp: (CalculatorMathOp * Number) option
  5. }
  6. // from the new design
  7. type CalculatorState =
  8. | ZeroState of ZeroStateData
  9. | AccumulatorState of AccumulatorStateData
  10. | AccumulatorWithDecimalState of AccumulatorStateData
  11. | ComputedState of ComputedStateData
  12. | ErrorState of ErrorStateData

Now that we have the basics of the new design, we need to define the other types referenced by it:

  1. and DigitAccumulator = string
  2. and PendingOp = (CalculatorMathOp * Number)
  3. and Number = float
  4. and NonZeroDigit=
  5. | One | Two | Three | Four
  6. | Five | Six | Seven | Eight | Nine
  7. and CalculatorMathOp =
  8. | Add | Subtract | Multiply | Divide
  9. and MathOperationResult =
  10. | Success of Number
  11. | Failure of MathOperationError
  12. and MathOperationError =
  13. | DivideByZero

And finally, we can define the services:

  1. // services used by the calculator itself
  2. type AccumulateNonZeroDigit = NonZeroDigit * DigitAccumulator -> DigitAccumulator
  3. type AccumulateZero = DigitAccumulator -> DigitAccumulator
  4. type AccumulateSeparator = DigitAccumulator -> DigitAccumulator
  5. type DoMathOperation = CalculatorMathOp * Number * Number -> MathOperationResult
  6. type GetNumberFromAccumulator = AccumulatorStateData -> Number
  7. // services used by the UI or testing
  8. type GetDisplayFromState = CalculatorState -> string
  9. type GetPendingOpFromState = CalculatorState -> string
  10. type CalculatorServices = {
  11. accumulateNonZeroDigit :AccumulateNonZeroDigit
  12. accumulateZero :AccumulateZero
  13. accumulateSeparator :AccumulateSeparator
  14. doMathOperation :DoMathOperation
  15. getNumberFromAccumulator :GetNumberFromAccumulator
  16. getDisplayFromState :GetDisplayFromState
  17. getPendingOpFromState :GetPendingOpFromState
  18. }

Note that because the state is much more complicated, I’ve added helper function getDisplayFromState that extracts the display text from the state.
This helper function will be used the UI or other clients (such as tests) that need to get the text to display.

I’ve also added a getPendingOpFromState, so that we can show the pending state in the UI as well.

Creating a state-based implementation

Now we can create a state-based implementation, using the pattern described earlier.

(The complete code is available in this gist.)

Let’s start with the main function that does the state transitions:

  1. let createCalculate (services:CalculatorServices) :Calculate =
  2. // create some local functions with partially applied services
  3. let handleZeroState = handleZeroState services
  4. let handleAccumulator = handleAccumulatorState services
  5. let handleAccumulatorWithDecimal = handleAccumulatorWithDecimalState services
  6. let handleComputed = handleComputedState services
  7. let handleError = handleErrorState
  8. fun (input,state) ->
  9. match state with
  10. | ZeroState stateData ->
  11. handleZeroState stateData input
  12. | AccumulatorState stateData ->
  13. handleAccumulator stateData input
  14. | AccumulatorWithDecimalState stateData ->
  15. handleAccumulatorWithDecimal stateData input
  16. | ComputedState stateData ->
  17. handleComputed stateData input
  18. | ErrorState stateData ->
  19. handleError stateData input

As you can see, it passes the responsibility to a number of handlers, one for each state, which will be discussed below.

But before we do that, I thought it might be instructive to compare the new state-machine based design with the (buggy!) one I did previously.

Here is the code from the previous one:

  1. let createCalculate (services:CalculatorServices) :Calculate =
  2. fun (input,state) ->
  3. match input with
  4. | Digit d ->
  5. let newState = updateDisplayFromDigit services d state
  6. newState //return
  7. | Op op ->
  8. let newState1 = updateDisplayFromPendingOp services state
  9. let newState2 = addPendingMathOp services op newState1
  10. newState2 //return
  11. | Action Clear ->
  12. let newState = services.initState()
  13. newState //return
  14. | Action Equals ->
  15. let newState = updateDisplayFromPendingOp services state
  16. newState //return

If we compare the two implementations, we can see that there has been a shift of emphasis from events to state.
You can see this by comparing how main pattern matching is done in the two implementations:

  • In the original version, the focus was on the input, and the state was secondary.
  • In the new version, the focus is on the state, and the input is secondary.

The focus on input over state, ignoring the context, is why the old version was such a bad design.

To repeat what I said above, many nasty bugs are caused by processing an event when you shouldn’t (as we saw with the original design).
I feel much more confident in the new design because of the explicit emphasis on state and context from the very beginning.

In fact, I’m not alone in noticing these kinds of issues.
Many people think that classic “event-driven programming“ is flawed
and recommend a more “state driven approach” (e.g. here and here),
just as I have done here.

Creating the handlers

We have already documented the requirements for each state transition, so writing the code is straightforward.
We’ll start with the code for the ZeroState handler:

  1. let handleZeroState services pendingOp input =
  2. // create a new accumulatorStateData object that is used when transitioning to other states
  3. let accumulatorStateData = {digits=""; pendingOp=pendingOp}
  4. match input with
  5. | Zero ->
  6. ZeroState pendingOp // stay in ZeroState
  7. | Digit digit ->
  8. accumulatorStateData
  9. |> accumulateNonZeroDigit services digit
  10. |> AccumulatorState // transition to AccumulatorState
  11. | DecimalSeparator ->
  12. accumulatorStateData
  13. |> accumulateSeparator services
  14. |> AccumulatorWithDecimalState // transition to AccumulatorWithDecimalState
  15. | MathOp op ->
  16. let nextOp = Some op
  17. let newState = getComputationState services accumulatorStateData nextOp
  18. newState // transition to ComputedState or ErrorState
  19. | Equals ->
  20. let nextOp = None
  21. let newState = getComputationState services accumulatorStateData nextOp
  22. newState // transition to ComputedState or ErrorState
  23. | Clear ->
  24. ZeroState None // transition to ZeroState and throw away any pending ops

Again, the real work is done in helper functions such as accumulateNonZeroDigit and getComputationState. We’ll look at those in a minute.

Here is the code for the AccumulatorState handler:

  1. let handleAccumulatorState services stateData input =
  2. match input with
  3. | Zero ->
  4. stateData
  5. |> accumulateZero services
  6. |> AccumulatorState // stay in AccumulatorState
  7. | Digit digit ->
  8. stateData
  9. |> accumulateNonZeroDigit services digit
  10. |> AccumulatorState // stay in AccumulatorState
  11. | DecimalSeparator ->
  12. stateData
  13. |> accumulateSeparator services
  14. |> AccumulatorWithDecimalState // transition to AccumulatorWithDecimalState
  15. | MathOp op ->
  16. let nextOp = Some op
  17. let newState = getComputationState services stateData nextOp
  18. newState // transition to ComputedState or ErrorState
  19. | Equals ->
  20. let nextOp = None
  21. let newState = getComputationState services stateData nextOp
  22. newState // transition to ComputedState or ErrorState
  23. | Clear ->
  24. ZeroState None // transition to ZeroState and throw away any pending op

Here is the code for the ComputedState handler:

  1. let handleComputedState services stateData input =
  2. let emptyAccumulatorStateData = {digits=""; pendingOp=stateData.pendingOp}
  3. match input with
  4. | Zero ->
  5. ZeroState stateData.pendingOp // transition to ZeroState with any pending op
  6. | Digit digit ->
  7. emptyAccumulatorStateData
  8. |> accumulateNonZeroDigit services digit
  9. |> AccumulatorState // transition to AccumulatorState
  10. | DecimalSeparator ->
  11. emptyAccumulatorStateData
  12. |> accumulateSeparator services
  13. |> AccumulatorWithDecimalState // transition to AccumulatorWithDecimalState
  14. | MathOp op ->
  15. // replace the pending op, if any
  16. let nextOp = Some op
  17. replacePendingOp stateData nextOp
  18. | Equals ->
  19. // replace the pending op, if any
  20. let nextOp = None
  21. replacePendingOp stateData nextOp
  22. | Clear ->
  23. ZeroState None // transition to ZeroState and throw away any pending op

The helper functions

Finally, let’s look at the helper functions:

The accumulator helpers are trivial — they just call the appropriate service and wrap the result in an AccumulatorData record.

  1. let accumulateNonZeroDigit services digit accumulatorData =
  2. let digits = accumulatorData.digits
  3. let newDigits = services.accumulateNonZeroDigit (digit,digits)
  4. let newAccumulatorData = {accumulatorData with digits=newDigits}
  5. newAccumulatorData // return

The getComputationState helper is much more complex — the most complex function in the entire code base, I should think.

It’s very similar to the updateDisplayFromPendingOp that we implemented before,
but there are a couple of changes:

  • The services.getNumberFromAccumulator code can never fail, because of the state-based approach. That makes life simpler!
  • The match result with Success/Failure code now returns two possible states: ComputedState or ErrorState.
  • If there is no pending op, we still need to return a valid ComputedState, which is what computeStateWithNoPendingOp does.
  1. let getComputationState services accumulatorStateData nextOp =
  2. // helper to create a new ComputedState from a given displayNumber
  3. // and the nextOp parameter
  4. let getNewState displayNumber =
  5. let newPendingOp =
  6. nextOp |> Option.map (fun op -> op,displayNumber )
  7. {displayNumber=displayNumber; pendingOp = newPendingOp }
  8. |> ComputedState
  9. let currentNumber =
  10. services.getNumberFromAccumulator accumulatorStateData
  11. // If there is no pending op, create a new ComputedState using the currentNumber
  12. let computeStateWithNoPendingOp =
  13. getNewState currentNumber
  14. maybe {
  15. let! (op,previousNumber) = accumulatorStateData.pendingOp
  16. let result = services.doMathOperation(op,previousNumber,currentNumber)
  17. let newState =
  18. match result with
  19. | Success resultNumber ->
  20. // If there was a pending op, create a new ComputedState using the result
  21. getNewState resultNumber
  22. | Failure error ->
  23. error |> ErrorState
  24. return newState
  25. } |> ifNone computeStateWithNoPendingOp

Finally, we have a new piece of code that wasn’t in the previous implementation at all!

What do you do when you get two math ops in a row? We just replace the old pending op (if any) with the new one (if any).

  1. let replacePendingOp (computedStateData:ComputedStateData) nextOp =
  2. let newPending = maybe {
  3. let! existing,displayNumber = computedStateData.pendingOp
  4. let! next = nextOp
  5. return next,displayNumber
  6. }
  7. {computedStateData with pendingOp=newPending}
  8. |> ComputedState

Completing the calculator

To complete the application, we just need to implement the services and the UI, in the same way as we did before.

As it happens, we can reuse almost all of the previous code. The only thing that has really changed
is the way that the input events are structured, which affects how the button handlers are created.

You can get the code for the state machine version of the calculator here.

If you try it out the new code, I think that you will find that it works first time, and feels much more robust. Another win for state-machine driven design!

Exercises

If you liked this design, and want to work on something similar, here are some exercises that you could do:

  • First, you could add some other operations. What would you have to change to implement unary ops such as 1/x and sqrt?
  • Some calculators have a back button. What would you have to do to implement this? Luckily all the data structures are immutable, so it should be easy!
  • Most calculators have a one-slot memory with store and recall. What would you have to change to implement this?
  • The logic that says that there are only 10 chars allowed on the display is still hidden from the design. How would you make this visible?

Summary

I hope you found this little experiment useful. I certainly learned something, namely:
don’t shortcut requirements gathering, and consider using a state based approach from the beginning — it might save you time in the long run!