Exit in Elm
Here’s an idiomatic Elm example that demonstrates the concept of exiting a program:
module Main exposing (main)
import Browser
import Html exposing (Html, div, text)
import Html.Events exposing (onClick)
import Platform.Cmd as Cmd
type alias Model =
{ exitStatus : Maybe Int }
init : () -> ( Model, Cmd Msg )
init _ =
( { exitStatus = Nothing }, Cmd.none )
type Msg
= Exit
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Exit ->
( { model | exitStatus = Just 3 }
, Cmd.none
)
view : Model -> Html Msg
view model =
div []
[ text <| "Exit status: " ++ Maybe.withDefault "Not exited" (Maybe.map String.fromInt model.exitStatus)
, div [ onClick Exit ] [ text "Exit with status 3" ]
]
main : Program () Model Msg
main =
Browser.element
{ init = init
, update = update
, view = view
, subscriptions = \_ -> Sub.none
}This Elm program demonstrates the concept of exiting a program, although it’s important to note that Elm, being primarily used for web applications, doesn’t have a direct equivalent to os.Exit as seen in the Go example.
Here’s how this Elm code works:
We define a
Modelthat includes anexitStatusof typeMaybe Int. This represents whether the program has “exited” and with what status code.The
initfunction sets up the initial state withexitStatusasNothing, indicating the program hasn’t exited yet.We define a
Msgtype with a single constructorExit, which will be used to trigger the “exit” action.In the
updatefunction, when anExitmessage is received, we update the model to set theexitStatustoJust 3, simulating an exit with status code 3.The
viewfunction displays the current exit status and provides a button to trigger the exit action.The
mainfunction sets up the Elm application usingBrowser.element.
To run this Elm program:
- Save the code in a file named
Exit.elm. - Use the Elm compiler to compile the code:
$ elm make Exit.elm --output=exit.js- Create an HTML file that includes the compiled JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Elm Exit Example</title>
</head>
<body>
<div id="elm"></div>
<script src="exit.js"></script>
<script>
var app = Elm.Main.init({
node: document.getElementById('elm')
});
</script>
</body>
</html>- Open the HTML file in a web browser to see the Elm application running.
This example demonstrates how to handle a concept similar to exiting in Elm, even though web applications don’t typically “exit” in the same way as command-line programs. Instead, we update the application state to reflect an “exited” status.