Skip to content

andThen2 : (a -> b -> Decoder c) -> Decoder a -> Decoder b -> Decoder c #25

@skyqrose

Description

@skyqrose

For combining multiple decode results in a way that might fail.

E.g if you have json that looks like

{
  "ids": [1, 2, 3, 4],
  "names": ["Not", "Enough", "Names"]
}

and you want to zip the two lists together, but fail if they're different lengths, you could do

Decode.Extra.andThen2
    (\ids names ->
        if List.length ids == List.length names
            Decode.succeed (List.zip ids names)
        else
            Decode.fail "expected the same number of ids and names"
    )
    (field "ids" (list int))
    (field "names" (list string))

Can be implemented as something like

andThen2 : (a -> b -> Decoder c) -> Decoder a -> Decoder b -> Decoder c
andThen2 f decoderA decoderB =
    map2 Tuple.pair decoderA decoderB
        |> andThen (\(a, b) -> f a b)

It's simple enough to use the tuple everywhere, but it reads a little better to be able to say andThen2 instead.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions