Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Get data constructor name as string

Let us say we have

data D = X Int | Y Int Int | Z String

I wish to have a function getDConst

getDConst :: D -> String

that returns either "X", "Y", or "Z", according to the data constructor used for its input. Is there a generic way to write this without having to do case on every data constructor? (I am ok with solutions relying on Data.Typeable or something similar)

like image 476
tohava Avatar asked Aug 18 '13 08:08

tohava


2 Answers

Found the solution myself, but leaving this question to help others:

import Data.Data
data D = X Int | Y Int Int deriving (Data,Typeable)

let result = show $ toConstr (X 3) -- result contains what we wanted
like image 196
tohava Avatar answered Nov 11 '22 18:11

tohava


If you don't want to use Typeable, you can also do this with Show.

getDConst :: D -> String
getDConst = head . words . show

Show will not output all the fields, because it is lazy. You can test it runing this code in ghci:

Prelude> data D = D [Int] deriving (Show)
Prelude> getDConst $ D [1..]
"D"
like image 11
MathematicalOrchid Avatar answered Nov 11 '22 18:11

MathematicalOrchid