Conversion from/to Term
I have a class for converting Term into a value, because I need to manipulate Term. I've been feeling that it would be nicer if we have that in Serialise class:
class Serialise a where
encode :: a -> Encoding
decode :: Decoder a
encodeList :: [a] -> Encoding
encodeList = defaultEncodeList
decodeList :: Decoder [a]
decodeList = defaultDecodeList
toTerm :: a -> Term
fromTerm :: Term -> Either String a
Hmm, why not a separate class?
We can do a generic conversion via the Encoding of course...
My separate class ended up in code duplication like this.
instance FromCBOR UTCTime where
fromCBOR (TTagged 0 s) = case s of
TString str -> maybe (Left "Couldn't parse UTCTime") Right $ parseUTCrfc3339 (T.unpack str)
_ -> Left "expecting String"
fromCBOR _ = Left "Expected timestamp (tag 0 or 1)"
formatUTCrfc3339 :: UTCTime -> String
formatUTCrfc3339 = formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%QZ"
parseUTCrfc3339 :: String -> Maybe UTCTime
parseUTCrfc3339 = parseTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%Q%Z"
I suppose there's no way to use Decoder for a Term (without re-serialisation)?
I suppose there's no way to use
Decoderfor aTerm(without re-serialisation)?
That is correct, there is currently no way to do this. It may be possible to write something like,
data DecodeResult s a = Done a
| More (Term -> DecoderResult s a)
| Fail String
decodeFromTerm :: forall a. Term -> Decoder s a -> DecodeResult s a
to short-cut out the serialisation step, but it wouldn't be trivial since DecoderAction is a rather large type.