Elm Calculator Part 7 - Add Dirty State

April 24, 2020 ยท 2 minute read

This post is part of a series. If you wish to support my work you can purchase the PDF book on gumroad.

This project uses Elm version 0.19


This allows users to overwrite the input area with a new number if the calculator is in a dirty state.

The way it works is if a user has just entered a number in, the input area is now dirty. Users can press enter again to keep pushing that same number on the stack. Or they can start typing a new number and it will over-write the existing number.

Dirty State

We need to add another piece of state to our model.

type alias Model =
    { stack : List Float
    , currentNum : String
    , error : Maybe String
    , dirty : Bool
    }


initialModel : Model
initialModel =
    { stack = []
    , currentNum = "0"
    , error = Nothing
    , dirty = False
    }

In the model update we need to add some logic around when the input field is dirty.

We need to do this to the Clear, Enter, InputOperator, SetDecimal, SetSign, and InputNumber messages.

Note: When I initially wrote the code I forgot to flip the flag on SetDecimal and SetSign. The Master branch has this fix. v0.7 does not.

Clear ->
    { model | currentNum = "0", dirty = False }

Enter ->
    ...
    { model
        | ...
        , dirty = True
    }

InputOperator operator ->
    ...
    { model
        | ...
        , dirty = True
    }

InputNumber num ->
    ...
    else if model.dirty then
        { model
            | ...
            , dirty = False
        }

The next chapter is going to add support for users to enter numbers into the calculator using their number pad on their keyboard.