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?
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With