我如何确定Haskell中的一个类型的大小? [英] How can I determine size of a type in Haskell?

查看:103
本文介绍了我如何确定Haskell中的一个类型的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我创建了一个类型如下:

  data RequestAck = 
RequestAck {ackOK :: Word32,ackMsgCode :: Word32}

我可以看到它的大小是2 * 4字节, 。

唯一的问题是,一旦我添加一个字段到类型中,我不得不记得更新我的常量。



是否有一个函数可以为我提供给定类型的大小,例如 t - > Int



接近我想要的功能是

gsize :: Data a => a - > Int



在Data.Generics.Schemes模块中,但我不想让我的类型成为<$ c的一个实例$ c $> Data 。



是否有更通用的解决方案?

可以肯定的是,我正在寻找一个在静态类型上运行的函数,例如,我不想传递一个实例,但是类型本身。

解决方案

这实际上取决于你如何将它转换为字节。



作为 Word32 ,没有固定大小。您看到的 Word32 可能是一个未应用的闭包,占用数百兆字节的空间。或者它可能是一个简单的盒装类型(它会大于4个字节)。或者它可能是某种内联标记类型(在这种情况下,它取决于平台)。或者它可能会被忽略(在这种情况下,不存在)。



只有当你真的可以说出什么大小的东西这是当你转换为二进制。如果你正在这样做与FFI接口,你可以使用 Foreign.Storable sizeOf 成员。当然,如果你想直接应用 sizeOf ,你需要为你的类型编写一个Storable实例。如果你通过Data.Binary序列化,那么只需要序列化这个东西。您通常不需要事先知道实际大小(如果您需要大小标头,只需将您计算大小的主体序列化为临时惰性字节串,然后取大小,然后写入大小和温度bytestring)。


Assume I created a type as follows:

data RequestAck = 
         RequestAck { ackOK :: Word32, ackMsgCode :: Word32 } 

I can see that it is 2 * 4 bytes big and make that a constant somewhere.

The only problems is that once I add a field to the type, I'd have to remember to update my constant.

Is there a function out there that will provide me with the size of a given type e.g., t -> Int?

The function that comes close to what I want is

gsize :: Data a => a -> Int

inside the Data.Generics.Schemes module, but I don't want to have to make my type an instance of Data.

Is there a more generic solution out there?

To be sure, I'm looking for a function that operates on the static type, e.g., I don't want to pass an instance, but the type itself.

解决方案

This really depends on how you're turning this into bytes.

As a Word32, there is no fixed size. What you see as a Word32 could be an unapplied closure taking up hundreds of megabytes of space. Or it could be a simple boxed type (which would be larger than 4 bytes). Or it could be some kind of inline tagged type (in which case it depends on the platform). Or it could be elided (in which case it doesn't exist).

The only time when you can really say what size something like this is is when you convert to binary. If you're doing this to interface with the FFI, you can use the sizeOf member of Foreign.Storable. Of course, you need to write a Storable instance for your type if you want to just apply sizeOf directly to it. If you're serializing via Data.Binary... well, just serialize the thing, really. You usually don't need to know the actual size beforehand (and if you do for a size header, just serialize the body you're counting the size of into a temporary lazy bytestring, then take the size, then write the size and temp bytestring).

这篇关于我如何确定Haskell中的一个类型的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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