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]
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]
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.