获取Haskell记录的字段名称作为字符串列表? [英] Get a Haskell record's field names as a list of strings?

查看:112
本文介绍了获取Haskell记录的字段名称作为字符串列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下几项:

pre code 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] 

没有模板Haskell。有人可以提供这样的示例实现可以完成?

解决方案

可以使用数据(大多数GHC版本)或Generic(7.2.x及以上)实例,GHC可以为您推导。下面是一个如何使用Data类型类转储记录字段的例子:

  { - #LANGUAGE DeriveDataTypeable# - } 

导入Data.Data

数据Rec = Rec {
alpha :: Int,
beta :: Double,
phi :: Float
)派生(Data,Typeable)

sample = Rec 1 2.3 4.5

main :: IO()
main = print。 constrFields。 toConstr $ sample


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?

解决方案

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:

{-# LANGUAGE DeriveDataTypeable #-}

import Data.Data

data Rec = Rec {
    alpha :: Int,
    beta  :: Double,
    phi   :: Float 
}  deriving (Data, Typeable)

sample = Rec 1 2.3 4.5

main :: IO ()
main = print . constrFields . toConstr $ sample 

这篇关于获取Haskell记录的字段名称作为字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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