Skip to content

How to parse a primitive type to a more constrained type? e.g. how to parse an 'IP' from a text field? #411

@Qqwy

Description

@Qqwy

I am looking to convert e.g. a string or text field that follows certain other rules into a more restricted datatype.
For instance, consider the 'server' field in this example https://github.com/kowainik/tomland/blob/main/test/examples/example.toml#L12.

We might want to parse this to a valid IP address datastructure (or fail parsing with a descriptive error). Vice-versa we of course want to be able to pretty-print this IP address back as a string.

So we have a Text -> Maybe IPAddress (or Text -> Either Text IPAddress) for the parsing, and IPAddress -> Text for the prettyprinting.

My hunch is that I'm looking for something that is very close to the signature of dimatch:

Toml.dimatch  :: (b -> Maybe a) -> (a -> b) -> Toml.TomlCodec a -> Toml.TomlCodec b

but with the opposite variance.

Toml.diparse  :: (b -> a) -> (a -> Maybe b) -> Toml.TomlCodec b -> Toml.TomlCodec a

(Of course, using an Either to keep track of the error messages is nicer than using Maybe here).

But maybe there is also a much simpler way that I'm missing?
I'm still very new to bidirectional parsing.

Metadata

Metadata

Assignees

No one assigned

    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