UnionEncoder allows you to build an
Encoder for a Dhall
record.
For example, let's take the following Haskell data type:
>>> :{
data Status = Queued Natural
| Result Text
| Errored Text
:}
And assume that we have the following Dhall union that we would like
to parse as a
Status:
< Result : Text
| Queued : Natural
| Errored : Text
>.Result "Finish successfully"
Our encoder has type
Encoder Status, but we can't
build that out of any smaller encoders, as
Encoders cannot be
combined. However, we can use an
UnionEncoder to build an
Encoder for
Status:
>>> :{
injectStatus :: Encoder Status
injectStatus = adapt >$< unionEncoder
( encodeConstructorWith "Queued" inject
>|< encodeConstructorWith "Result" inject
>|< encodeConstructorWith "Errored" inject
)
where
adapt (Queued n) = Left n
adapt (Result t) = Right (Left t)
adapt (Errored e) = Right (Right e)
:}
Or, since we are simply using the
ToDhall instance to inject
each branch, we could write
>>> :{
injectStatus :: Encoder Status
injectStatus = adapt >$< unionEncoder
( encodeConstructor "Queued"
>|< encodeConstructor "Result"
>|< encodeConstructor "Errored"
)
where
adapt (Queued n) = Left n
adapt (Result t) = Right (Left t)
adapt (Errored e) = Right (Right e)
:}