The Elm Architecture

This is a pretty minimal example of The Elm Architecture in a Jupyter notebook.

Imports

First, we have to import a few other modules


In [ ]:
import Browser
import Html exposing (..)
import Html.Events exposing (..)

Messages

Next we define our message "vocabulary". These are the various ways in which our model can be updated.


In [ ]:
type Msg = Inc | Dec

Model

Our model is simply an integer in this case. While it's not strictly necessary to create an alias for it, we'll include one for completeness; for more complex models you'll almost always have an alias.


In [ ]:
type alias Model = Int

Init and subscriptions

Next we define our init and subscriptions. Init passes the starting value in to our main program. Subscriptions is for telling our main program what events we want to receive.


In [ ]:
init : () -> (Model, Cmd Msg)
init _ = (0, Cmd.none)

subscriptions : Model -> Sub Msg
subscriptions _ = Sub.none

View

The view function renders our model.


In [ ]:
view : Model -> Html Msg
view model =
    div []
        [ button [ onClick Inc ] [ text "+" ]
        , div [] [ text (String.fromInt model) ]
        , button [ onClick Dec ] [ text "-" ]
        ]

Update

The update function takes a Msg and a Model, returning a new, updated Model.


In [ ]:
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case msg of
        Inc -> (model + 1, Cmd.none)
        Dec -> (model - 1, Cmd.none)

Main

Finally we tie everything together with main.


In [ ]:
main =
    Browser.element 
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }
    
-- compile-code