如何在 Haskell 中使记录类型位可寻址?
我的记录类型是 4 Word32。
data MyType = MyType {a :: Word32, b :: Word32, c :: Word32, d :: Word32 }
大多数时候,我想将这种类型视为4个单独的Word32。然而,有时我希望将其视为单个二进制数据流(128 位长,4 个 Word32 的串联)。我知道在Python中,我会为这个“结构”编写不同的访问器函数,这样我就可以以两种方式读取/修改它。但这是哈斯克尔。我想知道经验丰富的 Haskeller 会如何处理这个问题?
I have a record type that is 4 Word32.
data MyType = MyType {a :: Word32, b :: Word32, c :: Word32, d :: Word32 }
Most of the time, I want to treat this type as 4 separate Word32. However, sometimes I wish to treat it as a single stream of binary data (128 bits long, the concatenation of the 4 Word32). I know that in Python, I would write different accessor functions for this "structure", so that I could read/modify it in both ways. But this is Haskell. I am wondering how an experienced Haskeller would go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(2)
有一个类:-)
查看 Data.Bits 文档。完整的最小定义是提供
.&.
、.|.
、complement
、shift
的实现、rotate
、bitSize
和isSigned
(或其他一些可能的组合:有关详细信息,请参阅文档)。令人烦恼的是,您还必须实现Num
,尽管我并不完全清楚为什么他们要这样定义它。There's a class for that :-)
Check out the documentation for Data.Bits. A complete minimal definition is to provide an implementation of
.&.
,.|.
,complement
,shift
,rotate
,bitSize
andisSigned
(or a few other possible combinations: see the doc for details). Annoyingly you also have to implementNum
, although it's not entirely clear to me why they defined it that way.如果你真的希望它像一个由四个 word32 组成的结构,你可能想要使用严格/解压字段:
,让我们定义几个位调整函数:
现在你可以为这种类型编写 128 位访问器:
然后
abc d
字段,您可以使用 fclabels。您还可以创建一个 fclabel 双射函子(:<->:)
:If you really want it to be like a struct of four word32's, you might want to use strict/unpacked fields:
Then, let's define a couple of bit-fiddling functions:
Now you can just write 128-bit accessors for this type:
For the
a b c d
fields, you can just use fclabels. You can also make an fclabel bijective Functor(:<->:)
: