Signals in Elm
Our first example demonstrates how to handle signals in Elm. While Elm is primarily used for web applications and doesn’t directly interact with Unix signals, we can simulate a similar behavior using Elm’s built-in Platform.Sub for handling external inputs.
import Browser
import Html exposing (Html, div, text)
import Time
-- Model
type alias Model =
{ signal : String
, done : Bool
}
init : () -> (Model, Cmd Msg)
init _ =
( { signal = "", done = False }
, Cmd.none
)
-- Update
type Msg
= ReceiveSignal
| Finish
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
ReceiveSignal ->
( { model | signal = "SIGINT" }, Cmd.none )
Finish ->
( { model | done = True }, Cmd.none )
-- Subscriptions
subscriptions : Model -> Sub Msg
subscriptions _ =
Time.every 5000 (\_ -> ReceiveSignal)
-- View
view : Model -> Html Msg
view model =
div []
[ if not model.done then
text "Awaiting signal..."
else
text "Exiting"
, if model.signal /= "" then
div []
[ text ("Received signal: " ++ model.signal)
]
else
text ""
]
-- Main
main : Program () Model Msg
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}In this Elm program, we simulate signal handling using a subscription that triggers every 5 seconds (simulating a SIGINT). Here’s a breakdown of the code:
We define a
Modelthat keeps track of the received signal and whether the program is done.The
updatefunction handles two types of messages:ReceiveSignal(simulating receiving a signal) andFinish(simulating program termination).We use
subscriptionsto set up a recurring event that simulates receiving a signal every 5 seconds.The
viewfunction renders the current state, showing whether we’re awaiting a signal, have received one, or are exiting.In the
mainfunction, we set up the Elm application with our definedinit,update,subscriptions, andviewfunctions.
To run this Elm program:
- Save the code in a file named
Signals.elm. - Compile it using the Elm compiler:
elm make Signals.elm --output=signals.js. - Create an HTML file that includes the compiled JavaScript and run it in a web browser.
This example demonstrates how to handle external inputs in Elm, which is conceptually similar to handling signals in other languages, albeit in a web context rather than a system-level one.
Comments powered by Disqus