[Haskell-cafe] A generics question

Stefan Holdermans stefan at cs.uu.nl
Mon Jun 8 23:46:52 EDT 2009


Henry,

Jason pointed out:

> You'd get fromEnum and toEnum.  Which I think, would give you the  
> int mapping that you are after.
>
> fromEnum :: Enum a => a -> Int
> toEnum :: Enum a => Int -> a

To me, this would indeed seem the way to go for your particular example.

Moreover, as for generic producer functions in general, the pattern  
suggested by the Prelude would be to have

   c :: Color
   c = undefined

   convert :: Data a => Int -> a
   convert i x =
     let c = dataTypeConstrs (dataTypeOf x) !! (i-1)
     in  fromConstr c

and then use it as in

   convert 1 `asTypeOf` c

You'll find out that in most cases the (pseudo) "type annotation"  
isn't really needed and the type of the value to produce can be  
determined automatically by the context.

Cheers,

   Stefan


More information about the Haskell-Cafe mailing list