Data.Codec.Argonaut.Variant
- Package
- purescript-codec-argonaut
- Repository
- garyb/purescript-codec-argonaut
#variantMatch Source
variantMatch :: forall ro ri rl. RowToList ri rl => VariantCodec rl ri ro => Record ri -> JsonCodec (Variant ro)
Builds a codec for a variant from a record, similar to the way
Variant.match
works to pattern match on a variant.
Commonly used to write decoders for sum-types, by providing a mapping from
and to a Variant from that type and then using dimap
.
Each field in the record accepts an Either
, where Right
is used to
specify a codec used for the constructor, and Left
is used to specify a
static value (generally as Left unit
for nullary constructors).
The variant will be encoded as a JSON object of the form
{ "tag": <name>, "value": <value> }
, where <name>
is the name of the
variant case, and <value>
is the associated value (omitted in the case
of static Left
-defined values).
codecMaybeMatch ∷ ∀ a. JA.JsonCodec a → JA.JsonCodec (Maybe a)
codecMaybeMatch codecA =
dimap toVariant fromVariant
(JAV.variantMatch
{ just: Right codecA
, nothing: Left unit
})
where
toVariant = case _ of
Just a → V.inj (SProxy ∷ _ "just") a
Nothing → V.inj (SProxy ∷ _ "nothing") unit
fromVariant = V.match
{ just: Just
, nothing: \_ → Nothing
}
#variant Source
variant :: JsonCodec (Variant ())
Builds codecs for variants in combination with variantCase
.
Provides an alternative means of building variant codecs to that of
variantMatch
, often for cases where the codec is being constructed
with a fold or some other similar technique.
codecMaybe ∷ ∀ a. JA.JsonCodec a → JA.JsonCodec (Maybe a)
codecMaybe codecA =
dimap toVariant fromVariant
(JAV.variant
# JAV.variantCase _Just (Right codecA)
# JAV.variantCase _Nothing (Left unit))
where
toVariant = case _ of
Just a → V.inj _Just a
Nothing → V.inj _Nothing unit
fromVariant = V.case_
# V.on _Just Just
# V.on _Nothing (const Nothing)
_Just = SProxy ∷ SProxy "just"
_Nothing = SProxy ∷ SProxy "nothing"
#VariantCodec Source
class VariantCodec (rl :: RowList) (ri :: Row Type) (ro :: Row Type) | rl -> ri ro where
The class used to enable the building of Variant
codecs from a record of
codecs.
Members
variantCodec :: RLProxy rl -> Record ri -> JsonCodec (Variant ro)
Instances
VariantCodec Nil () ()
(VariantCodec rs ri' ro', Cons sym (Either a (JsonCodec a)) ri' ri, Cons sym a ro' ro, IsSymbol sym, TypeEquals co (Either a (JsonCodec a))) => VariantCodec (Cons sym co rs) ri ro