Skip to content

feat: add decoder Computation Expression#227

Merged
MangelMaxime merged 4 commits intothoth-org:mainfrom
njlr:feature/decoder-syntax
Apr 18, 2026
Merged

feat: add decoder Computation Expression#227
MangelMaxime merged 4 commits intothoth-org:mainfrom
njlr:feature/decoder-syntax

Conversation

@njlr
Copy link
Copy Markdown
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

@MangelMaxime MangelMaxime force-pushed the feature/decoder-syntax branch from e9a63c1 to 8f165b5 Compare April 18, 2026 12:50
@MangelMaxime MangelMaxime changed the title feature/decoder-syntax feat: add decoder Computation Expression Apr 18, 2026
@MangelMaxime MangelMaxime merged commit 9d95782 into thoth-org:main Apr 18, 2026
3 checks passed
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.

2 participants