optionalWith: A generalized optional modifier.
#78
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Current state of optional field parsing with
optionalLet’s say we have a record with an optional
flagfield:The appropiate codec for this would look like:
This setup is convenient, as it supports multiple JSON inputs:
{}is parsed as{ flag: Nothing }{ "flag": true }is parsed as{ flag: Just true }{ "flag": false }is parsed as{ flag: Just false }Introducing
optionalWithHowever, in many use cases, working with a
Maybe Booleanisn’t ideal. Often, we’d prefer to use a plainBoolean, treating bothNothingandJust falseas false:With the current version of
codec-argonaut, we’d need to define bothSampleandSample2, along with conversion functions between them.To avoid this, the PR introduces a new modifier:
optionalWith, a more flexible version ofoptional.Here’s how it can be used:
This codec handles the following cases directly:
{}is decoded as{ flag: false }{ "flag": true }is decoded as{ flag: true }{ "flag": false }is decoded as{ flag: false }Other Usecases
This pattern is especially useful when working with JavaScript APIs, where fields are often omitted instead of explicitly set to a default or “empty” value.
Other examples where
optionalWithis useful include:Maybe (Maybe a)to justMaybe a, useful for fields that can be either null or missingBonus:
optionalWithis a generalization ofoptional, which can now internally be redefined as:As a result, this MR introduces no code duplication. Tests are added that verify the behavior.