Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode optional string in Elm

Tags:

encode

elm

I would like to encode a Maybe String to string if it has a concrete value, or null if it's Nothing.

At the moment, I use a helper function encodeOptionalString myStr to get the desired effect. I was wondering if there's a more Elm-like way of doing this. I really like the API of elm-json-decode-pipeline that allows me to write Decode.nullable Decode.string for decoding.

encodeOptionalString : Maybe String -> Encode.Value
encodeOptionalString s =
    case s of
        Just s_ ->
            Encode.string s_

        Nothing ->
            Encode.null
like image 378
viam0Zah Avatar asked Jul 15 '20 16:07

viam0Zah


1 Answers

You could generalize this into an encodeNullable function yourself:

encodeNullable : (value -> Encode.Value) -> Maybe value -> Encode.Value
encodeNullable valueEncoder maybeValue =
    case maybeValue of
        Just value ->
            valueEncoder value

        Nothing ->
            Encode.null

Or if you want a slightly shorter ad hoc expression:

maybeString
|> Maybe.map Encode.string
|> Maybe.withDefault Encode.null
like image 92
glennsl Avatar answered Oct 02 '22 15:10

glennsl