How to get a list of constructors for a type?

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.

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

I've put some of Oleg's code on hackage, named polytypeable.
import Data.PolyTypeable main = print [polyTypeOf Nothing, polyTypeOf Just]
This prints
[Maybe a1,a1 -> Maybe a1]
To get a list of the actual constructors you need to derive
Data.Data.Data and use that.
-- Lennart
On Wed, Dec 30, 2009 at 8:46 PM, Claude Heiland-Allen
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 _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
participants (3)
-
Claude Heiland-Allen
-
Gregory Propf
-
Lennart Augustsson