Created
March 7, 2018 07:44
-
-
Save mfeineis/0aa89feeef4ef0c9f19d35a8de96a85d to your computer and use it in GitHub Desktop.
A snippet for making a `Json.Decoder` from a result
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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