Skip to content

Opposite of Codec.invmap would be useful #105

@Choc13

Description

@Choc13

So I find myself writing the following quite a bit:

type VariableName = VariableName of string

module VariableName =
    let value (VariableName x) = x

module VariableNameCodec =
    let ofDomain = VariableName.value
    let toDomain = VariableName

    let encoder = ofDomain >> JsonEncode.string

    let decoder = JsonDecode.string >> Result.map toDomain

    let codec = decoder, encoder    

And then I saw Codec.invmap and assumed that would satisfy me and I could write JsonCodec.string |> Codec.invmap toDomain ofDomain. However invmap works in the other direction, mapping the JsonValue part of the codec rather than the VariableName part of the codec. Or alternatively, the input to the decoder and the output of the encoder.

I think it would be nice to add the following alongside invmap.

let inline contrainvmap f g (decoder, encoder) =
        map (map f) decoder, contramap g encoder

Although I'm not sure the name is quite correct because actually on the decoder it's mapping twice (once through the function and then through the result type it returns) and also because I'm not sure if "contrainvmap" is the correct category theory based name for this thing.

Thoughts on adding this (assuming I've not overlooked something that already exists which does this)?

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