loading...
Cover image for Elm Calculator Part 6 - Supporting Negative Numbers

Elm Calculator Part 6 - Supporting Negative Numbers

pianomanfrazier profile image Ryan Frazier Originally published at pianomanfrazier.com on ・2 min read

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"
    ]

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

type Msg
    = ...
    | SetSign

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 }

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

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

Posted on by:

pianomanfrazier profile

Ryan Frazier

@pianomanfrazier

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.

Discussion

pic
Editor guide