cborg icon indicating copy to clipboard operation
cborg copied to clipboard

Conversion from/to Term

Open fumieval opened this issue 9 years ago • 3 comments

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

fumieval avatar Oct 31 '16 05:10 fumieval

Hmm, why not a separate class?

We can do a generic conversion via the Encoding of course...

dcoutts avatar Feb 09 '17 17:02 dcoutts

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)?

fumieval avatar Feb 10 '17 05:02 fumieval

I suppose there's no way to use Decoder for a Term (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.

bgamari avatar Aug 01 '17 17:08 bgamari