Search code examples
encodeelm

Encode optional string in 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

Solution

  • 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