Elm Calculator Part 6 - Supporting Negative Numbers
Ryan Frazier

Ryan Frazier @pianomanfrazier

About: I love static site generators, Elm, JavaScript and building things for the web. In my previous life I was a working classical pianist. I try to combine music and programming when I can.

Joined:
May 10, 2019

Elm Calculator Part 6 - Supporting Negative Numbers

Publish Date: Apr 17 '20
4 0

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.

Comments 0 total

    Add comment