From 83034116b02497576d97bffc9e91a5476cc60d41 Mon Sep 17 00:00:00 2001 From: Noah Loomans Date: Wed, 13 Sep 2017 21:36:32 +0200 Subject: decode union type --- src/client/elm/Main.elm | 58 ++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 45 insertions(+), 13 deletions(-) (limited to 'src/client/elm/Main.elm') diff --git a/src/client/elm/Main.elm b/src/client/elm/Main.elm index 8e1e9c8..de1f1fe 100644 --- a/src/client/elm/Main.elm +++ b/src/client/elm/Main.elm @@ -1,8 +1,7 @@ module Main exposing (..) --- import Html.Attributes exposing (..) import Html exposing (..) -import Json.Decode exposing (string, Decoder) +import Json.Decode exposing (Decoder, andThen, fail, string, succeed) import Json.Decode.Pipeline exposing (decode, required) @@ -15,7 +14,9 @@ main = , subscriptions = subscriptions } -type alias Flags = Json.Decode.Value + +type alias Flags = + Json.Decode.Value type alias Model = @@ -24,7 +25,7 @@ type alias Model = type alias User = - { type_ : String + { type_ : UserType , value : String } @@ -35,31 +36,62 @@ type UserType | Room | Student + init : Flags -> ( Model, Cmd msg ) init flags = case Json.Decode.decodeValue decodeUsers flags of Ok user -> - (Model user, Cmd.none) + ( Model user, Cmd.none ) Err err -> Debug.crash err + decodeUsers : Decoder (List User) -decodeUsers = Json.Decode.list decodeUser +decodeUsers = + Json.Decode.list decodeUser + decodeUser : Decoder User decodeUser = - decode User - |> required "type" string - |> required "value" string + decode User + |> required "type" decodeUserType + |> required "value" string + + +decodeUserType : Json.Decode.Decoder UserType +decodeUserType = + string + |> andThen + (\s -> + case s of + "s" -> + succeed Student + + "c" -> + succeed Class + + "t" -> + succeed Teacher + + "r" -> + succeed Room + + _ -> + fail ("What the f*ck is " ++ s ++ "?") + ) + + +update : msg -> Model -> ( Model, Cmd msg ) +update msg model = + ( model, Cmd.none ) -update : msg -> Model -> (Model, Cmd msg) -update msg model = (model, Cmd.none) view : Model -> Html msg view model = - text <| toString model + text <| toString model + subscriptions : Model -> Sub msg subscriptions model = - Sub.none \ No newline at end of file + Sub.none -- cgit v1.1