Module

Data.Codec.Argonaut.Variant

Package
purescript-codec-argonaut
Repository
garyb/purescript-codec-argonaut

#variantMatch Source

variantMatch :: forall rl ri ro. 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 (Proxy ∷ _ "just") a
    Nothing → V.inj (Proxy ∷ _ "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 = Proxy ∷ Proxy "just"
  _Nothing = Proxy ∷ Proxy "nothing"

#variantCase Source

variantCase :: forall l a r r'. IsSymbol l => Cons l a r r' => Proxy l -> Either a (JsonCodec a) -> JsonCodec (Variant r) -> JsonCodec (Variant r')

#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

Instances