Data.Codec.JSON.Variant
- Package
- purescript-codec-json
- Repository
- garyb/purescript-codec-json
#variantMatch Source
variantMatch :: forall rl ri ro. RowToList ri rl => VariantCodec rl ri ro => Record ri -> Codec (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. CJ.Codec a → CJ.Codec (Maybe a)
codecMaybeMatch codecA =
dimap toVariant fromVariant
(CJV.variantMatch
{ just: Right codecA
, nothing: Left unit
})
where
toVariant = case _ of
Just a → V.inj (Proxy ∷ _ "just") a
Nothing → V.inj (Proxy ∷ _ "nothing") unit
fromVariant = V.match
{ just: Just
, nothing: \_ → Nothing
}
#variant Source
variant :: Codec (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. CJ.Codec a → CJ.Codec (Maybe a)
codecMaybe codecA =
dimap toVariant fromVariant
(CJV.variant
# CJV.variantCase _Just (Right codecA)
# CJV.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 = Proxy ∷ Proxy "just"
_Nothing = Proxy ∷ Proxy "nothing"
#VariantCodec Source
class VariantCodec :: RowList Type -> Row Type -> Row Type -> Constraintclass VariantCodec (rl :: RowList Type) (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 :: forall proxy. proxy rl -> Record ri -> Codec (Variant ro)
Instances
VariantCodec Nil () ()(VariantCodec rs ri' ro', Cons sym (Either a (Codec a)) ri' ri, Cons sym a ro' ro, IsSymbol sym, TypeEquals co (Either a (Codec a))) => VariantCodec (Cons sym co rs) ri ro