layout: post
title: “Calculator Walkthrough: Part 2”
description: “Testing the design with a trial implementation”
categories: [“Worked Examples”]
seriesId: “Annotated walkthroughs”
seriesOrder: 2


In this post, I’ll continue developing a simple pocket calculator app, like this:

Calculator image

In the previous post, we completed a first draft of the design, using only types (no UML diagrams!).

Now it’s time to create a trial implementation that uses the design.

Doing some real coding at this point acts as a reality check. It ensures that the domain model actually makes sense and is not too abstract.
And of course, it often drives more questions about the requirements and domain model.

First implementation

So let’s try implementing the main calculator function, and see how we do.

First, we can immediately create a skeleton that matches each kind of input and processes it accordingly.

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

You can see that this skeleton has a case for each type of input to handle it appropriately.
Note that in all cases, a new state is returned.

This style of writing a function might look strange though. Let’s look at it a bit more closely.

First, we can see that createCalculate is the not the calculator function itself, but a function that returns another function.
The returned function is a value of type Calculate — that’s what the :Calculate at the end means.

Here’s just the top part:

  1. let createCalculate (services:CalculatorServices) :Calculate =
  2. fun (input,state) ->
  3. match input with
  4. // code

Since it is returning a function, I chose to write it using a lambda. That’s what the fun (input,state) -> is for.

But I could have also written it using an inner function, like this

  1. let createCalculate (services:CalculatorServices) :Calculate =
  2. let innerCalculate (input,state) =
  3. match input with
  4. // code
  5. innerCalculate // return the inner function

Both approaches are basically the same* — take your pick!

* Although there might be some performance differences.

Dependency injection of services

But createCalculate doesn’t just return a function, it also has a services parameter.
This parameter is used for doing the “dependency injection” of the services.

That is, the services are only used in createCalculate itself, and are not visible in the function of type Calculate that is returned.

The “main” or “bootstrapper” code that assembles all the components for the application would look something like this:

  1. // create the services
  2. let services = CalculatorServices.createServices()
  3. // inject the services into the "factory" method
  4. let calculate = CalculatorImplementation.createCalculate services
  5. // the returned "calculate" function is of type Calculate
  6. // and can be passed into the UI, for example
  7. // create the UI and run it
  8. let form = new CalculatorUI.CalculatorForm(calculate)
  9. form.Show()

Implementation: handling digits

Now let’s start implementing the various parts of the calculation function. We’ll start with the digits handling logic.

To keep the main function clean, let’s pass the reponsibility for all the work to a helper function updateDisplayFromDigit, like this:

  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

Note that I’m creating a newState value from the result of updateDisplayFromDigit and then returning it as a separate step.

I could have done the same thing in one step, without an explicit newState value, as shown below:

  1. let createCalculate (services:CalculatorServices) :Calculate =
  2. fun (input,state) ->
  3. match input with
  4. | Digit d ->
  5. updateDisplayFromDigit services d state

Neither approach is automatically best. I would pick one or the other depending on the context.

For simple cases, I would avoid the extra line as being unnecessary, but sometimes having an explicit return value is more readable.
The name of the value tells you an indication of the return type, and it gives you something to watch in the debugger, if you need to.

Alright, let’s implement updateDisplayFromDigit now. It’s pretty straightforward.

  • first use the updateDisplayFromDigit in the services to actually update the display
  • then create a new state from the new display and return it.
  1. let updateDisplayFromDigit services digit state =
  2. let newDisplay = services.updateDisplayFromDigit (digit,state.display)
  3. let newState = {state with display=newDisplay}
  4. newState //return

Implementation: handling Clear and Equals

Before we move onto the implementation of the math operations, lets look at handling Clear and Equals, as they are simpler.

For Clear, just init the state, using the provided initState service.

For Equals, we check if there is a pending math op. If there is, run it and update the display, otherwise do nothing.
We’ll put that logic in a helper function called updateDisplayFromPendingOp.

So here’s what createCalculate looks like now:

  1. let createCalculate (services:CalculatorServices) :Calculate =
  2. fun (input,state) ->
  3. match input with
  4. | Digit d -> // as above
  5. | Op op -> // to do
  6. | Action Clear ->
  7. let newState = services.initState()
  8. newState //return
  9. | Action Equals ->
  10. let newState = updateDisplayFromPendingOp services state
  11. newState //return

Now to updateDisplayFromPendingOp. I spent a few minutes thinking about, and I’ve come up with the following algorithm for updating the display:

  • First, check if there is any pending op. If not, then do nothing.
  • Next, try to get the current number from the display. If you can’t, then do nothing.
  • Next, run the op with the pending number and the current number from the display. If you get an error, then do nothing.
  • Finally, update the display with the result and return a new state.
  • The new state also has the pending op set to None, as it has been processed.

And here’s what that logic looks like in imperative style code:

  1. // First version of updateDisplayFromPendingOp
  2. // * very imperative and ugly
  3. let updateDisplayFromPendingOp services state =
  4. if state.pendingOp.IsSome then
  5. let op,pendingNumber = state.pendingOp.Value
  6. let currentNumberOpt = services.getDisplayNumber state.display
  7. if currentNumberOpt.IsSome then
  8. let currentNumber = currentNumberOpt.Value
  9. let result = services.doMathOperation (op,pendingNumber,currentNumber)
  10. match result with
  11. | Success resultNumber ->
  12. let newDisplay = services.setDisplayNumber resultNumber
  13. let newState = {display=newDisplay; pendingOp=None}
  14. newState //return
  15. | Failure error ->
  16. state // original state is untouched
  17. else
  18. state // original state is untouched
  19. else
  20. state // original state is untouched

Ewww! Don’t try that at home!

That code does follow the algorithm exactly, but is really ugly and also error prone (using .Value on an option is a code smell).

On the plus side, we did make extensive use of our “services”, which has isolated us from the actual implementation details.

So, how can we rewrite it to be more functional?

Bumping into bind

The trick is to recognize that the pattern “if something exists, then act on that value” is exactly the bind pattern discussed here
and here.

In order to use the bind pattern effectively, it’s a good idea to break the code into many small chunks.

First, the code if state.pendingOp.IsSome then do something can be replaced by Option.bind.

  1. let updateDisplayFromPendingOp services state =
  2. let result =
  3. state.pendingOp
  4. |> Option.bind ???

But remember that the function has to return a state.
If the overall result of the bind is None, then we have not created a new state, and we must return the original state that was passed in.

This can be done with the built-in defaultArg function which, when applied to an option, returns the option’s value if present, or the second parameter if None.

  1. let updateDisplayFromPendingOp services state =
  2. let result =
  3. state.pendingOp
  4. |> Option.bind ???
  5. defaultArg result state

You can also tidy this up a bit as well by piping the result directly into defaultArg, like this:

  1. let updateDisplayFromPendingOp services state =
  2. state.pendingOp
  3. |> Option.bind ???
  4. |> defaultArg <| state

I admit that the reverse pipe for state looks strange — it’s definitely an acquired taste!

Onwards! Now what about the parameter to bind? When this is called, we know that pendingOp is present, so we can write a lambda with those parameters, like this:

  1. let result =
  2. state.pendingOp
  3. |> Option.bind (fun (op,pendingNumber) ->
  4. let currentNumberOpt = services.getDisplayNumber state.display
  5. // code
  6. )

Alternatively, we could create a local helper function instead, and connect it to the bind, like this:

  1. let executeOp (op,pendingNumber) =
  2. let currentNumberOpt = services.getDisplayNumber state.display
  3. /// etc
  4. let result =
  5. state.pendingOp
  6. |> Option.bind executeOp

I myself generally prefer the second approach when the logic is complicated, as it allows a chain of binds to be simple.
That is, I try to make my code look like:

  1. let doSomething input = return an output option
  2. let doSomethingElse input = return an output option
  3. let doAThirdThing input = return an output option
  4. state.pendingOp
  5. |> Option.bind doSomething
  6. |> Option.bind doSomethingElse
  7. |> Option.bind doAThirdThing

Note that in this approach, each helper function has a non-option for input but always must output an option.

Using bind in practice

Once we have the pending op, the next step is to get the current number from the display so we can do the addition (or whatever).

Rather than having a lot of logic, I’m going keep the helper function (getCurrentNumber) simple.

  • The input is the pair (op,pendingNumber)
  • The output is the triple (op,pendingNumber,currentNumber) if currentNumber is Some, otherwise None.

In other words, the signature of getCurrentNumber will be pair -> triple option, so we can be sure that is usable with the Option.bind function.

How to convert the pair into the triple? This can be done just by using Option.map to convert the currentNumber option to a triple option.
If the currentNumber is Some, then the output of the map is Some triple.
On the other hand, if the currentNumber is None, then the output of the map is None also.

  1. let getCurrentNumber (op,pendingNumber) =
  2. let currentNumberOpt = services.getDisplayNumber state.display
  3. currentNumberOpt
  4. |> Option.map (fun currentNumber -> (op,pendingNumber,currentNumber))
  5. let result =
  6. state.pendingOp
  7. |> Option.bind getCurrentNumber
  8. |> Option.bind ???

We can rewrite getCurrentNumber to be a bit more idiomatic by using pipes:

  1. let getCurrentNumber (op,pendingNumber) =
  2. state.display
  3. |> services.getDisplayNumber
  4. |> Option.map (fun currentNumber -> (op,pendingNumber,currentNumber))

Now that we have a triple with valid values, we have everything we need to write a helper function for the math operation.

  • It takes a triple as input (the output of getCurrentNumber)
  • It does the math operation
  • It then pattern matches the Success/Failure result and outputs the new state if applicable.
  1. let doMathOp (op,pendingNumber,currentNumber) =
  2. let result = services.doMathOperation (op,pendingNumber,currentNumber)
  3. match result with
  4. | Success resultNumber ->
  5. let newDisplay = services.setDisplayNumber resultNumber
  6. let newState = {display=newDisplay; pendingOp=None}
  7. Some newState //return something
  8. | Failure error ->
  9. None // failed

Note that, unlike the earlier version with nested ifs, this version returns Some on success and None on failure.

Displaying errors

Writing the code for the Failure case made me realize something.
If there is a failure, we are not displaying it at all, just leaving the display alone. Shouldn’t we show an error or something?

Hey, we just found a requirement that got overlooked! This is why I like to create an implementation of the design as soon as possible.
Writing real code that deals with all the cases will invariably trigger a few “what happens in this case?” moments.

So how are we going to implement this new requirement?

In order to do this, we’ll need a new “service” that accepts a MathOperationError and generates a CalculatorDisplay.

  1. type SetDisplayError = MathOperationError -> CalculatorDisplay

and we’ll need to add it to the CalculatorServices structure too:

  1. type CalculatorServices = {
  2. // as before
  3. setDisplayNumber: SetDisplayNumber
  4. setDisplayError: SetDisplayError
  5. initState: InitState
  6. }

doMathOp can now be altered to use the new service. Both Success and Failure cases now result in a new display, which in turn is wrapped in a new state.

  1. let doMathOp (op,pendingNumber,currentNumber) =
  2. let result = services.doMathOperation (op,pendingNumber,currentNumber)
  3. let newDisplay =
  4. match result with
  5. | Success resultNumber ->
  6. services.setDisplayNumber resultNumber
  7. | Failure error ->
  8. services.setDisplayError error
  9. let newState = {display=newDisplay;pendingOp=None}
  10. Some newState //return something

I’m going to leave the Some in the result, so we can stay with Option.bind in the result pipeline*.

* An alternative would be to not return Some, and then use Option.map in the result pipeline

Putting it all together, we have the final version of updateDisplayFromPendingOp.
Note that I’ve also added a ifNone helper that makes defaultArg better for piping.

  1. // helper to make defaultArg better for piping
  2. let ifNone defaultValue input =
  3. // just reverse the parameters!
  4. defaultArg input defaultValue
  5. // Third version of updateDisplayFromPendingOp
  6. // * Updated to show errors on display in Failure case
  7. // * replaces awkward defaultArg syntax
  8. let updateDisplayFromPendingOp services state =
  9. // helper to extract CurrentNumber
  10. let getCurrentNumber (op,pendingNumber) =
  11. state.display
  12. |> services.getDisplayNumber
  13. |> Option.map (fun currentNumber -> (op,pendingNumber,currentNumber))
  14. // helper to do the math op
  15. let doMathOp (op,pendingNumber,currentNumber) =
  16. let result = services.doMathOperation (op,pendingNumber,currentNumber)
  17. let newDisplay =
  18. match result with
  19. | Success resultNumber ->
  20. services.setDisplayNumber resultNumber
  21. | Failure error ->
  22. services.setDisplayError error
  23. let newState = {display=newDisplay;pendingOp=None}
  24. Some newState //return something
  25. // connect all the helpers
  26. state.pendingOp
  27. |> Option.bind getCurrentNumber
  28. |> Option.bind doMathOp
  29. |> ifNone state // return original state if anything fails

Using a “maybe” computation expression instead of bind

So far, we’ve being using “bind” directly. That has helped by removing the cascading if/else.

But F# allows you to hide the complexity in a different way, by creating computation expressions.

Since we are dealing with Options, we can create a “maybe” computation expression that allows clean handling of options.
(If we were dealing with other types, we would need to create a different computation expression for each type).

Here’s the definition — only four lines!

  1. type MaybeBuilder() =
  2. member this.Bind(x, f) = Option.bind f x
  3. member this.Return(x) = Some x
  4. let maybe = new MaybeBuilder()

With this computation expression available, we can use maybe instead of bind, and our code would look something like this:

  1. let doSomething input = return an output option
  2. let doSomethingElse input = return an output option
  3. let doAThirdThing input = return an output option
  4. let finalResult = maybe {
  5. let! result1 = doSomething
  6. let! result2 = doSomethingElse result1
  7. let! result3 = doAThirdThing result2
  8. return result3
  9. }

In our case, then we can write yet another version of updateDisplayFromPendingOp — our fourth!

  1. // Fourth version of updateDisplayFromPendingOp
  2. // * Changed to use "maybe" computation expression
  3. let updateDisplayFromPendingOp services state =
  4. // helper to do the math op
  5. let doMathOp (op,pendingNumber,currentNumber) =
  6. let result = services.doMathOperation (op,pendingNumber,currentNumber)
  7. let newDisplay =
  8. match result with
  9. | Success resultNumber ->
  10. services.setDisplayNumber resultNumber
  11. | Failure error ->
  12. services.setDisplayError error
  13. {display=newDisplay;pendingOp=None}
  14. // fetch the two options and combine them
  15. let newState = maybe {
  16. let! (op,pendingNumber) = state.pendingOp
  17. let! currentNumber = services.getDisplayNumber state.display
  18. return doMathOp (op,pendingNumber,currentNumber)
  19. }
  20. newState |> ifNone state

Note that in this implementation, I don’t need the getCurrentNumber helper any more, as I can just call services.getDisplayNumber directly.

So, which of these variants do I prefer?

It depends.

  • If there is a very strong “pipeline” feel, as in the ROP approach, then I prefer using an explicit bind.
  • On the other hand, if I am pulling options from many different places, and I want to combine them in various ways, the maybe computation expression makes it easier.

So, in this case, I’ll go for the last implementation, using maybe.

Implementation: handling math operations

Now we are ready to do the implementation of the math operation case.

First, if there is a pending operation, the result will be shown on the display, just as for the Equals case.
But in addition, we need to push the new pending operation onto the state as well.

For the math operation case, then, there will be two state transformations, and createCalculate will look like this:

  1. let createCalculate (services:CalculatorServices) :Calculate =
  2. fun (input,state) ->
  3. match input with
  4. | Digit d -> // as above
  5. | Op op ->
  6. let newState1 = updateDisplayFromPendingOp services state
  7. let newState2 = addPendingMathOp services op newState1
  8. newState2 //return

We’ve already defined updateDisplayFromPendingOp above.
So we just need addPendingMathOp as a helper function to push the operation onto the state.

The algorithm for addPendingMathOp is:

  • Try to get the current number from the display. If you can’t, then do nothing.
  • Update the state with the op and current number.

Here’s the ugly version:

  1. // First version of addPendingMathOp
  2. // * very imperative and ugly
  3. let addPendingMathOp services op state =
  4. let currentNumberOpt = services.getDisplayNumber state.display
  5. if currentNumberOpt.IsSome then
  6. let currentNumber = currentNumberOpt.Value
  7. let pendingOp = Some (op,currentNumber)
  8. let newState = {state with pendingOp=pendingOp}
  9. newState //return
  10. else
  11. state // original state is untouched

Again, we can make this more functional using exactly the same techniques we used for updateDisplayFromPendingOp.

So here’s the more idiomatic version using Option.map and a newStateWithPending helper function:

  1. // Second version of addPendingMathOp
  2. // * Uses "map" and helper function
  3. let addPendingMathOp services op state =
  4. let newStateWithPending currentNumber =
  5. let pendingOp = Some (op,currentNumber)
  6. {state with pendingOp=pendingOp}
  7. state.display
  8. |> services.getDisplayNumber
  9. |> Option.map newStateWithPending
  10. |> ifNone state

And here’s one using maybe:

  1. // Third version of addPendingMathOp
  2. // * Uses "maybe"
  3. let addPendingMathOp services op state =
  4. maybe {
  5. let! currentNumber =
  6. state.display |> services.getDisplayNumber
  7. let pendingOp = Some (op,currentNumber)
  8. return {state with pendingOp=pendingOp}
  9. }
  10. |> ifNone state // return original state if anything fails

As before, I’d probably go for the last implementation using maybe. But the Option.map one is fine too.

Implementation: review

Now we’re done with the implementation part. Let’s review the code:

  1. let updateDisplayFromDigit services digit state =
  2. let newDisplay = services.updateDisplayFromDigit (digit,state.display)
  3. let newState = {state with display=newDisplay}
  4. newState //return
  5. let updateDisplayFromPendingOp services state =
  6. // helper to do the math op
  7. let doMathOp (op,pendingNumber,currentNumber) =
  8. let result = services.doMathOperation (op,pendingNumber,currentNumber)
  9. let newDisplay =
  10. match result with
  11. | Success resultNumber ->
  12. services.setDisplayNumber resultNumber
  13. | Failure error ->
  14. services.setDisplayError error
  15. {display=newDisplay;pendingOp=None}
  16. // fetch the two options and combine them
  17. let newState = maybe {
  18. let! (op,pendingNumber) = state.pendingOp
  19. let! currentNumber = services.getDisplayNumber state.display
  20. return doMathOp (op,pendingNumber,currentNumber)
  21. }
  22. newState |> ifNone state
  23. let addPendingMathOp services op state =
  24. maybe {
  25. let! currentNumber =
  26. state.display |> services.getDisplayNumber
  27. let pendingOp = Some (op,currentNumber)
  28. return {state with pendingOp=pendingOp}
  29. }
  30. |> ifNone state // return original state if anything fails
  31. let createCalculate (services:CalculatorServices) :Calculate =
  32. fun (input,state) ->
  33. match input with
  34. | Digit d ->
  35. let newState = updateDisplayFromDigit services d state
  36. newState //return
  37. | Op op ->
  38. let newState1 = updateDisplayFromPendingOp services state
  39. let newState2 = addPendingMathOp services op newState1
  40. newState2 //return
  41. | Action Clear ->
  42. let newState = services.initState()
  43. newState //return
  44. | Action Equals ->
  45. let newState = updateDisplayFromPendingOp services state
  46. newState //return

Not bad — the whole implementation is less than 60 lines of code.

Summary

We have proved that our design is reasonable by making an implementation — plus we found a missed requirement.

In the next post, we’ll implement the services and the user interface to create a complete application.

The code for this post is available in this gist on GitHub.