Thoth.Json
Thoth.Json copied to clipboard
feature/decoder-syntax
This PR adds a Computation Expression for decoding.
It is called decoder and works as one might expect:
type Item =
| Book of title : string * year : int * stars : int
| Author of fullName : string * stars : int
module Item =
let decode : Decoder<Item> =
decoder {
let! title = Decode.optional "title" Decode.string
let! fullName = Decode.optional "fullName" Decode.string
let! stars = Decode.field "stars" Decode.int
match title, fullName with
| Some title, None ->
let! year = Decode.field "year" Decode.int
return Book (title, year, stars)
| None, Some fullName ->
return Author (fullName, stars)
| Some _, Some _ ->
return! Decode.fail $"Must not specify `title` and `fullName` properties"
| None, None ->
return! Decode.fail $"Must specify either a `title` or `fullName` property"
}
The primary use-case is complex conditional decoders where Decode.andThen is typically used. Elm lacks CEs so has to lean heavily on andThen, but we don't have this limitation! :smile:
Related: https://github.com/thoth-org/Thoth.Json/issues/121