Signals in Elm

Here’s the translation of the Go code to Elm, along with explanations in Markdown format suitable for Hugo:

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:

  1. We define a Model that keeps track of the received signal and whether the program is done.

  2. The update function handles two types of messages: ReceiveSignal (simulating receiving a signal) and Finish (simulating program termination).

  3. We use subscriptions to set up a recurring event that simulates receiving a signal every 5 seconds.

  4. The view function renders the current state, showing whether we’re awaiting a signal, have received one, or are exiting.

  5. In the main function, we set up the Elm application with our defined init, update, subscriptions, and view functions.

To run this Elm program:

  1. Save the code in a file named Signals.elm.
  2. Compile it using the Elm compiler: elm make Signals.elm --output=signals.js.
  3. 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.