Skip to content

Instantly share code, notes, and snippets.

@clohr
Last active January 30, 2017 03:36
Show Gist options
  • Select an option

  • Save clohr/d7fff885cf6d90166a85b1a65cc62ea2 to your computer and use it in GitHub Desktop.

Select an option

Save clohr/d7fff885cf6d90166a85b1a65cc62ea2 to your computer and use it in GitHub Desktop.
Updating deep records in Elm
module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onInput)
main =
program
{ init = init
, update = update
, view = view
, subscriptions = (always Sub.none)
}
-- INIT
type alias Model =
{ a :
{ b :
{ c : Int
}
}
}
initialModel =
{ a = { b = { c = 1 } } }
init : ( Model, Cmd Msg )
init =
( initialModel, Cmd.none )
-- UPDATE
type Msg
= UpdateC String
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
UpdateC val ->
(updateModel model val) ! [ Cmd.none ]
-- HELPER
updateModel : Model -> String -> Model
updateModel model val =
let
levelA =
model.a
levelB =
levelA.b
intVal =
Result.withDefault 0 <| String.toInt val
in
{ model
| a =
{ levelA
| b =
{ levelB | c = intVal }
}
}
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input [ value <| toString model.a.b.c, onInput <| UpdateC ] []
, text <| toString model
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment