DEV Community

Cover image for Elm Calculator Part 6 - Supporting Negative Numbers
Ryan Frazier
Ryan Frazier

Posted on • Originally published at pianomanfrazier.com on

Elm Calculator Part 6 - Supporting Negative Numbers

This post is part of a series. To see all published posts in the series see the tag "elm calculator book".If you wish to support my work you can purchase the book on gumroad.

This project uses Elm version 0.19

  • Part 1 - Introduction
  • Part 2 - Project Setup
  • Part 3 - Add CSS
  • Part 4 - Basic Operations
  • Part 5 - Adding Decimal Support
  • Part 6 - Supporting Negative Numbers (this post)
  • Part 7 - Add Dirty State
  • Part 8 - Support Keypad Input
  • Part 9 - Combination Key Input
  • Part 10 - Testing
  • Part 11 - Netlify Deployment

Users need to be able to input negative numbers. Since negatives are different than the subtract operation we need to handle this separately.

Many RPN calculators I have seen have a toggle sign button.

section : Html Msg
section =
    div [ class "section" ]
    [ ...
    , cell (onClick SetSign) Single White "+/-"
    , cell (onClick Enter) Single Yellow "Enter"
    ]
Enter fullscreen mode Exit fullscreen mode

And then let's add the message type and update the model.

type Msg
    = ...
    | SetSign
Enter fullscreen mode Exit fullscreen mode

We need to do some string checking to make this work.

update : Msg -> Model -> Model
update msg model =
    case msg of
        ...
        SetSign ->
            -- don't allow the user to make a negative zero
            if model.currentNum == "0" then
                model

            -- drop the negative sign from the string
            else if String.startsWith "-" model.currentNum then
                { model | currentNum = String.dropLeft 1 model.currentNum }
            -- add the negative sign
            else
                { model | currentNum = "-" ++ model.currentNum }
Enter fullscreen mode Exit fullscreen mode

And that's it. We now have a working calculator.

The next few chapters will be adding some nice extra features.

Discussion (0)