[Haskell-cafe] How to get a list of constructors for a type?

Claude Heiland-Allen claudiusmaximus at goto10.org
Wed Dec 30 15:46:43 EST 2009


Gregory Propf wrote:
> Say I have something like
> 
> data DT a = Foo a | Bar a | Boo a
> 
> I want something like a list of the constructors of DT, perhaps as [TypeRep].  I'm using Data.Typeable but can't seem to find what I need in there.  Everything there operates over constructors, not types.

The approach below won't work in general because the constructors may 
have different (argument) types, but for the above:

     [Foo, Bar, Boo] :: [a -> DT a]

And you could manually build a list of constructor types, as a try:

     [typeOf Nothing, typeOf Just] :: [TypeRep]

which doesn't work, due to polymorphic ambiguity, so you'd have to:

     [typeOf (Nothing :: Maybe Int), typeOf (Just :: Int -> Maybe Int)]

In general, maybe Data.Dynamic is what you need, but I don't think that 
can handle polymorphic values yet either.

What do you want to do with the list of constructors once you have them?

Where are they defined?


Claude
-- 
http://claudiusmaximus.goto10.org


More information about the Haskell-Cafe mailing list