Time · An Introduction to Elmの例では、初期化時のModelのtimeがゼロだったので、現在時間で初期化したかった。やる前は瞬殺と思っていたのだが、いやいやどうにも苦戦した。どうやるのか理解するのに結構苦労してしまった。関数脳への道は遠い...。
結果こうなった。
module Main exposing (Model, Msg(..), init, main, subscriptions, update, view) import Browser import Html exposing (..) import Task import Time -- MAIN main = Browser.element { init = init , view = view , update = update , subscriptions = subscriptions } -- MODEL type alias Model = { zone : Time.Zone , time : Time.Posix } init : () -> ( Model, Cmd Msg ) init _ = ( Model Time.utc (Time.millisToPosix 0) , Task.perform SetSystemTime Time.now ) -- UPDATE type Msg = Tick Time.Posix | SetSystemTime Time.Posix update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of Tick newTime -> ( { model | time = newTime } , Cmd.none ) SetSystemTime newTime -> ( { model | time = newTime }, Cmd.none ) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Time.every 1000 Tick -- VIEW view : Model -> Html Msg view model = let hour = Time.toHour model.zone model.time |> String.fromInt |> String.pad 2 '0' minute = Time.toMinute model.zone model.time |> String.fromInt |> String.pad 2 '0' second = Time.toSecond model.zone model.time |> String.fromInt |> String.pad 2 '0' in h1 [] [ text ("時間" ++ hour ++ ":" ++ minute ++ ":" ++ second) ]