Form <select> with union type

194 views
Skip to first unread message

Simone Vittori

unread,
Jul 27, 2016, 11:25:46 AM7/27/16
to Elm Discuss
I'm building a language selector and I'd like to map the options to a union type.

Here's what I tried:

import Json.Decode exposing (Decoder, customDecoder, string)

{-| Currently supported languages. -}
type Language
    = English
    | Japanese


{-| A JSON decoder of Language. -}
languageDecoder : Decoder Language
languageDecoder =
    customDecoder string fromStringLanguage


fromStringLanguage : String -> Result String Language
fromStringLanguage str =
    case str of
        "English" -> Ok English
        "Japanese" -> Ok Japanese
        other -> Err ("Invalid language: " ++ other)

And here's how I'm using it:

-- MODEL

type alias Model = Language


-- UPDATE

type Msg
    = Change Language

update : Msg -> Model -> Model
update msg model =
    case msg of
        Change language -> language


-- VIEW

view : Model -> Html Msg
view model =
    Html.form []
        [ select [ on "change" <| Json.Decode.map Change languageDecoder ]
            (List.map (viewOption model) ["English", "Japanese"])
        ]

It does compile successfully, but when I select another option from the dropdown list, nothing happens. Any ideas?
Is this the right way of decoding a union type?

Yosuke Torii

unread,
Jul 28, 2016, 12:32:13 PM7/28/16
to Elm Discuss
Hi Simone,

I wrote the fixed version here (copy & paste to Try Elm).
Union type was not wrong. The `on` function assumes an event object to be decoded, but you expect a string.
So I used `targetValue` decoder, which is a shortcut for `e.target.value`.


2016年7月28日木曜日 0時25分46秒 UTC+9 Simone Vittori:

Simone Vittori

unread,
Jul 29, 2016, 5:04:11 AM7/29/16
to Elm Discuss
Oh I see! Makes totally sense :)

Thank you very much!
Reply all
Reply to author
Forward
0 new messages