列出Haskell类型的构造函数名称?

问题描述

conNameOf使我可以显示给定数据的构造函数名称,因为该类型是Generic的实例。

我想要的是类似的东西。对于给定的类型,我想获取构造函数名称的完整列表。例如:

data Nat = Z | S Nat
  deriving (Generic)

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

是否存在类似constrNames的东西?如果没有,我该怎么写?

解决方法

软件包conNames中模块Generics.Deriving.ConNames的函数generic-deriving提供了此功能。它使用给定类型的术语,尽管未使用其值,因此可以使用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)

给予:

λ> main
["Z","S"]