Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a Haskell record's field names as a list of strings?

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?

like image 228
Ana Avatar asked Dec 10 '11 16:12

Ana


1 Answers

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 
like image 65
Nathan Howell Avatar answered Oct 05 '22 22:10

Nathan Howell