Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List constructor names of a Haskell type?

conNameOf allows me to display the constructor name of a given piece of data, given that type is an instance of Generic.

What I'd like is something similar. For a given type, I want to get the full list of constructor names. For example:

data Nat = Z | S Nat
  deriving (Generic)

-- constrNames (Proxy :: Proxy Nat) == ["Z", "S"]

Does something like constrNames exist? If not, how can I write it?

like image 787
Dan Burton Avatar asked Mar 03 '23 04:03

Dan Burton


1 Answers

The function conNames from module Generics.Deriving.ConNames in package generic-deriving provides this functionality. It takes a term of the given type, though its value is not used, so you can use undefined:

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics
import Generics.Deriving.ConNames
import Data.Proxy

data Nat = Z | S Nat deriving (Generic)

main = print $ conNames (undefined :: Nat)

gives:

λ> main
["Z","S"]
like image 114
K. A. Buhr Avatar answered Mar 07 '23 09:03

K. A. Buhr