定义联合数据类型的可存储实例 [英] Defining storable instance for union data types

查看:74
本文介绍了定义联合数据类型的可存储实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何定义可存储的数据类型的矢量实例(由GHC基本类型组成):

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.

推荐答案

您必须编码用于实例化类型的构造器.

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.

这篇关于定义联合数据类型的可存储实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆