Elm is a functional programming language to develop websites’ front end. Evan Czaplicki designed Elm in 2012.
Some practical applications of Elm in programming platforms are as follows:
This answer will go through the steps of creating a simple flip coin web application in Elm. The purpose of this is to get familiar with web applications using Elm.
To create a web application in Elm programming, we must understand the basic Elm architecture, which follows the Model-View-Update (MVU).
Model: It is used to hold the state of the application. The coin flip app will hold the initial state of the coin.
View: It is used to show our application as HTML
Update: It is used to update the state of the application.
A few basic things that need to be done to set up an application in Elm are given below:
In the code snippet below, we import the fundamental modules, functions, attributes, etc.
Browser
: This module is used to build web applications.
Html
: This module is used to build the user interface (UI).
import Browserimport Html exposing (..)import Html.Events exposing (..)import Random
In the code snippet below, we are setting the application’s initial state.
It defines the customer data type, Model
.
The current state of applications is stored in coinFace
.
type alias Model ={coinFace : Int}
update
functionIn the code snippet below, we define the update
function which takes two arguments (msg
, Model
) and returns Model
(updated state).
type Msg= Roll| NewFace Intupdate : Msg -> Model -> (Model, Cmd Msg)update msg model =case msg ofRoll ->( model, Random.generate NewFace (Random.int 0 1))NewFace newFace ->( Model newFace, Cmd.none)
view
functionIn the code snippet below, we define the view
function. It takes the parameter Model
and creates an HTML user interface.
The button
element is used to trigger changes between states.
view : Model -> Html Msgview model =div [][h3 [] [ text (if model.coinFace == 0 then "Head" else "Tail") ],button [ onClick Roll ] [ text "Roll a dice" ]]
main
functionIn the code snippet below, define main
, which is the entry point to our application.
main =Browser.element{ init = init, update = update, subscriptions = subscriptions, view = view}
The complete code for the flip coin web application is given below in src/Main.elm
. We can run the application by pressing the “Run” button.
{ "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/random": "1.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": {} } }
Free Resources