Skip to content

Conversation

@njlr
Copy link
Contributor

@njlr njlr commented Oct 30, 2025

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! 😄

Related: #121

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant