Sal
Sal

Reputation: 4326

Defining storable instance for union data types

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.

Upvotes: 1

Views: 442

Answers (1)

dflemstr
dflemstr

Reputation: 26157

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.

Upvotes: 4

Related Questions