Select Page

Elm is a functional programming language. It compiles to javascript. It promises a couple things that you won’t find with javascript such as no runtime errors, helpful error messages, and reliable refactoring.

We will make an Elm app based on the same structure of the basic examples found at Elm’s official guide.

Elm Architecture

This is the basic idea behind Elm’s architecture.

Model -> View -> Update -> Message

Set the app directory structure for your first Elm app like this.

+ FirstApp
--elm.json
   + src
     --FirstApp.elm

Elm 18 recently went under a huge breaking upgrade which changed some things about the language. While I have heard that 90% of Elm 18 code works in 19 it has not been my experience.

For example the Html.beginnerProgram module is no longer a thing.

It has been replaced by Browser.sandbox which works just as well if not better.

module FirstApp exposing(..)
import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
-- MAIN
main =
  Browser.sandbox { init = init, update = update, view = view }
-- MODEL
type alias Model = Int
init : Model
init =
  0
-- UPDATE
type Msg
  = Add
  | Subtract
update : Msg -> Model -> Model
update msg model =
  case msg of
    Add ->
      model + 1
    Subtract ->
      model - 1
-- VIEW
view : Model -> Html Msg
view model =
  div []
    [ button [ onClick Subtract ] [ text "-" ]
    , div [] [ text (String.fromInt model) ]
    , button [ onClick Add ] [ text "+" ]
    ]

Compile your first Elm app and let’s take a look at it.

elm make ./src/Firstapp.elm

Elm outputs an index.html which you can open in any browser.

Improve Your App

The app is great don’t get me wrong but what about adding a reset button?

Module Firstapp exposing(...)

import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)

-- MAIN

main =
  Browser.sandbox { init = init, update = update, view = view }

-- MODEL

type alias Model = Int

init : Model
init =
  0

-- UPDATE

type Msg
  = Add
  | Subtract
  | Reset


update : Msg -> Model -> Model
update msg model =
  case msg of
    Add ->
      model + 1

    Subtract ->
      model - 1

    Reset ->
       0

-- VIEW

view : Model -> Html Msg
view model =
  div []
    [ button [ onClick Subtract ] [ text "-" ]
    , div [] [ text (String.fromInt model) ]
    , button [ onClick Add ] [ text "+" ]
    , button [ onClick Reset ] [ text "Reset" ]
    ]

Now compile your first Elm app again.

elm make ./src/Firstapp.elm

How It Works

The imports like Firstapp is based on the name of the source file, Firstapp.elm, makes sense?

The Browser module takes in the view, model, update, and messages in an instantiation of the sandbox function.

The onClick function defines an action when the button defined in the model is clicked.

error: