获取 Haskell 记录的字段名称作为字符串列表?
假设我有以下内容:
data Rec = Rec {
alpha :: Int,
beta :: Double,
phi :: Float
}
sample = Rec 1 2.3 4.5
我了解 Template Haskell & reify
函数可以获取记录的字段名称。那就是:
print $(f sample) --> ["alpha", "beta", "phi"]
还有一种说法是,这可以在没有 Template Haskell 的情况下完成。有人可以提供一个可以完成此操作的示例实现吗?
Say I have the following:
data Rec = Rec {
alpha :: Int,
beta :: Double,
phi :: Float
}
sample = Rec 1 2.3 4.5
I understand Template Haskell & the reify
function can get me the record's field names. That is:
print $(f sample) --> ["alpha", "beta", "phi"]
There is also a claim that this can be done without Template Haskell. Can someone provide an example implementation for this can be accomplished?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它可以使用数据(大多数 GHC 版本)或通用(7.2.x 及更高版本)实例来完成,GHC 可以为您派生该实例。以下是如何使用数据类型类转储记录字段的示例:
It can be done with a Data (most GHC versions) or Generic (7.2.x and up) instance, which GHC can derive for you. Here's an example of how to dump record fields with the Data typeclass: