2

Is it possible to create a function in Haskell which returns a list of the constructors for a data type?

It should work like this:

ghci> getConstructors Bool
[True, False]
ghci> getConstructors Maybe
[Nothing, Just]
Cœur
  • 37,241
  • 25
  • 195
  • 267
Netsu
  • 355
  • 4
  • 13
  • let's assume for a moment that `Bool` and `Maybe` where values of some type - already for `Maybe` your resulting list would have one element of type `Maybe a` and one of type `a -> Maybe a` so it would not be a valid list - having said this: you probably get something very similar by using [Typeable](https://hackage.haskell.org/package/base-4.8.0.0/docs/Data-Typeable.html) – Random Dev May 22 '15 at 13:54
  • The `Data` typeclass has something along those lines, but it's terrifying. – AJF May 22 '15 at 15:32

1 Answers1

14

Think about this: what would be the type of the list? Nothing has type Maybe a but Just has type a -> Maybe a.

You can look at generics though. Using the package syb:

Prelude> import Data.Data
Prelude Data.Data> dataTypeConstrs $ dataTypeOf (Just 4)
[Nothing,Just]

Note that here [Nothing,Just] is just how it's printed on screen, it's not actually a list containing the two constructors.

Prelude Data.Data> :t dataTypeConstrs (dataTypeOf (Just 4))
dataTypeConstrs (dataTypeOf (Just 4)) :: [Constr]

Anyway, having a list with [Nothing,Just] (even if that was correct Haskell) would not be really useful. You wouldn't be able to do anything with the values inside it as you wouldn't know their types.

tomferon
  • 4,993
  • 1
  • 23
  • 44