Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

haskell - Where are the Winery types indexed?

I want to build an alternate Winery schema decoder. So I had a look at some of the encoded schemas:

*Codec.Winery> B.unpack $ serialiseSchema $ schema (Proxy :: Proxy Void)
[4,5,0]
*Codec.Winery> B.unpack $ serialiseSchema $ schema (Proxy :: Proxy Bool)
[4,6]
*Codec.Winery> B.unpack $ serialiseSchema $ schema (Proxy :: Proxy Int)
[4,16]
*Codec.Winery> B.unpack $ serialiseSchema $ schema (Proxy :: Proxy Integer)
[4,16]
*Codec.Winery> B.unpack $ serialiseSchema $ schema (Proxy :: Proxy Void)
[4,5,0]
*Codec.Winery> B.unpack $ serialiseSchema $ schema (Proxy :: Proxy ())
[4,3,0]

I know the first number is the schema version. I understand that the Int can be encoded as an Integer since it is strictly smaller. But what about the others?

I tried to compare it to the indexed of the types mentioned in bookstrapSchema but they don't seem to match.

How can I make sense of these numbers?

question from:https://stackoverflow.com/questions/65856745/where-are-the-winery-types-indexed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

They match, but some take arguments. Ignoring the version number 4, the encoding [5,0] means an SVariant with zero alternatives, basically a sum type with no constructors, AKA Void:

data Void

On the other hand [3,0] means an SProduct with zero fields, namely a type with a single nullary constructor, AKA ():

data () = ()

I'd suggest looking at sum and product types other than these "degenerate" ones, and studying the output of pretty-printing the schemas alongside their serializations:

import Codec.Winery
import qualified Data.ByteString as B
import Data.Proxy
import Prettyprinter

main = do
  let s = schema (Proxy :: Proxy (Either Int String))
  print $ B.unpack . serialiseSchema $ s
  print $ pretty s

The encoding and pretty-printed schema here are:

[4,5,2,4,76,101,102,116,3,1,16,5,82,105,103,104,116,3,1,2,7]
Left Integer | Right [Char]

which means:

[4                       -- version 4
,5,2                     -- SVariant with 2 alternatives, namely:
  ,4,76,101,102,116      --   4-character constructor "Left" for
    ,3,1                 --     SProduct with 1 field
      ,16                --       consisting of an SInteger
  ,5,82,105,103,104,116  --   5-character constructor "Right" for
    ,3,1                 --     SProduct with 1 field
      ,2                 --       consisting of an SVector
        ,7]              --         of SChar
       

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...