Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Alt for decoder functions #36

Closed
mlms13 opened this issue May 13, 2019 · 1 comment
Closed

Add Alt for decoder functions #36

mlms13 opened this issue May 13, 2019 · 1 comment
Labels
enhancement New feature or request

Comments

@mlms13
Copy link
Owner

mlms13 commented May 13, 2019

We currently have examples in tests where we use <|> from Result or Option to essentially fall through multiple decoders until we find one that works. This isn't ideal because it requires you to run each decoder, even if the first one succeeds.

Arguably, Decode.oneOf already solves this use case, but in the spirit of making decoders more composable (#23), we could add Decode.alt that looks something like this:

type stringOrInt = S(string) | I(int);
let decode =
  Decode.alt(
    Decode.map(v => S(v), Decode.string),
    Decode.map(v => I(v), Decode.intFromNumber),
  );

// Ok(I(3));
let decoded = decode(Js.Json.number(3.0));
  • Since you'd be applying alt to the decode functions themselves (instead of the output option/result), we should be able to only run subsequent decoders if we haven't yet found a successful value
  • We can probably rewrite oneOf to use this alt function?
  • If possible, this is a good candidate to use the TriedMultiple error to track the failure from each decoder that has been attempted (Add a new ParseError constructor "TriedMultiple" #26)
@mlms13 mlms13 added the enhancement New feature or request label May 13, 2019
@mlms13 mlms13 closed this as completed in 7c607c4 May 25, 2019
@mlms13
Copy link
Owner Author

mlms13 commented May 25, 2019

TriedMultiple is still coming, and I haven't yet written tests to prove that the alt implementation is lazy (it definitely is). Other than that, this is done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant