Defining storable instance for union data types

2019-08-02 23:57发布

How do you define the storable vector instance for a data type like below (composed from GHC primitive types):

data Atoms =  I GHC.Int.Int32|S GHC.Int.Int16 -- define a union data type

I checked this storable tutorial but it works only for vectors of same types, not union like above.

1条回答
狗以群分
2楼-- · 2019-08-03 00:53

You have to encode which constructor you used to instantiate the type somehow.

You can for example add a byte that specifies the index of the constructor that was used. This means that the values above could be stored like this:

Haskell    Binary
I 3     -> 00 00 00 00 03
S 4     -> 01 00 04 XX XX
              ^ Data
           ^ Constructor index
XX = unused byte

Then, when you want to deserialize a value from a byte string, you peek the first byte, see which index it is, and choose the constructor to use (and what to peek off next) based on that.

查看更多
登录 后发表回答