Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

elm
counter

How to create a simple counter in Elm

Sohaib Bin Mohsin

Overview

In this Answer, we’ll create a simple counter using Elm.

Code

We can create a simple counter in Elm using the following code. Press the “Run” button below to see the output of the code.

{
    "type": "application",
    "source-directories": [
        "src"
    ],
    "elm-version": "0.19.0",
    "dependencies": {
        "direct": {
            "elm/browser": "1.0.1",
            "elm/core": "1.0.2",
            "elm/html": "1.0.0",
            "elm/time": "1.0.0",
            "elm/http": "2.0.0",
            "elm/json": "1.1.3"
        },
        "indirect": {
            "elm/url": "1.0.0",
            "elm/virtual-dom": "1.0.2",
            "elm/bytes": "1.0.8",
            "elm/file": "1.0.5"
        }
    },
    "test-dependencies": {
        "direct": {},
        "indirect": {}
    }
}

Explanation

  • Line 1: We expose everything in the file Main.elm by using (..).

  • Lines 2–4: We import Browser, Html, and Html.Events libraries and expose the required functions from those libraries.

  • Line 6: We use -- to write comments in Elm.

  • Line 7: We declare the type of Model and set it to Int. We do this to keep track of the counter, which is usually an integer.

  • Lines 9–10: We write the signature for initModel, which has the alias Model, and initialize it with 0.

Note: The Update function takes a Msg and a Model and returns an updated version of the Model.

  • Line 13: We create a type called Msg that has two possible values—Add and Subtract. These are the only Msg values that the user needs to send in our program.

  • Line 15: We create the signature of update function, which takes two parameters, Msg and Model, and returns a Model.

  • Line 16–22: We define two cases in the update function. If the Msg is Add, then we update the Model by adding 1. If the Msg is Subtract, then we update the Model by subtracting 1.

  • Lines 25–30: We provide model as an input to the view function and create a div with no attributes (this acts like a container).

    • Inside the div, we create a button that has an onClick attribute which calls the Add update on every click. It also has the text “+”. We also create a button for Subtract, which has the text “-”.
    • Between these buttons, we create another div, with text, that displays the number of the counter. Since text takes a String as input while the model is an Int, we use the String.fromInt function to convert Int to String.
  • Line 33: We call the Browser.sandbox function inside main. This function requires three parameters init, view, and update.

RELATED TAGS

elm
counter
RELATED COURSES

View all Courses

Keep Exploring