Skip to content

Instantly share code, notes, and snippets.

@mfeineis
Created March 7, 2018 07:44
Show Gist options
  • Save mfeineis/0aa89feeef4ef0c9f19d35a8de96a85d to your computer and use it in GitHub Desktop.
Save mfeineis/0aa89feeef4ef0c9f19d35a8de96a85d to your computer and use it in GitHub Desktop.
A snippet for making a `Json.Decoder` from a result
-- From https://robots.thoughtbot.com/5-common-json-decoders#1---decoding-union-types
fromResult : Result String a -> Decoder a
fromResult result =
case result of
Ok a -> JD.succeed a
Err errorMessage -> JD.fail errorMessage
parseDirection : String -> Result String Direction
parseDirection string =
case string of
"north" -> Ok North
"south" -> Ok South
"east" -> Ok East
"west" -> Ok West
_ -> Err ("Invalid direction: " ++ string)
direction : Decoder Direction
direction =
Decode.string |> Decode.andThen (fromResult << parseDirection)
date : Decoder Date
date =
Decode.string |> Decode.andThen (fromResult << Date.fromString)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment