[Haskell-beginners] Enumerated types
Brent Yorgey
byorgey at seas.upenn.edu
Sun Dec 27 09:14:45 EST 2009
On Sun, Dec 27, 2009 at 02:42:48PM +0100, legajid wrote:
> Hello,
>
> I have some trouble evaluating Enum class.
> Following is my source:
>
> data Authors= Buzzati | Werber | Verne | Ray | Asimov | Voltaire deriving
> (Enum, Show)
>
> auths=[Buzzati .. Verne] ++ enumFrom Ray
> pref=take 3 auths
> -- 1 disp_pref=mapM_ (putStrLn) pref
This is a type error since putStrLn expects a String and pref is a
list of Authors. But the 'deriving Show' means that you can use the
'show' function to convert:
disp_pref = mapM_ (putStrLn . show) pref
In fact, since print = putStrLn . show, you can just say
disp_pref = mapM_ print pref
> 2. Like fromEnum gives data constructor index, is it possible with toEnum
> (or other way) to get the nth constructor of the given type ?
> eg : 2 applied to Authors (not in scope ?) would give Verne
Yes, with toEnum. Just use e.g. 'toEnum 2'. How does it know that
you want an Author and not some other Enum type? Why, through the
magic of type inference! As long as you use 'toEnum 2' in a context
where an Author value is expected it will evaluate to Verne.
> 3. tried to take 'succ' of last tag in enumeration
> How to detect the end of an enumeration ? Can i get the maxbound index ?
Yes, if you add 'Bounded' to the list of derived classes, then
'maxBound' gives you the last one.
-Brent
More information about the Beginners
mailing list