[Haskell-beginners] Enumerated types
Patrick LeBoutillier
patrick.leboutillier at gmail.com
Sun Dec 27 09:10:21 EST 2009
Hi,
On Sun, Dec 27, 2009 at 8:42 AM, legajid <legajid at free.fr> 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
putStrLn wants a String as argument, here you are passing an Authors. Try this:
disp_pref=mapM_ (putStrLn . show) pref
>
> auth1 = Buzzati
> auth2 = succ auth1 -- Werber
> auth3 = pred Asimov -- Ray
> num_auth4=fromEnum Verne -- 2
> -- 2 toEnum
You can use toEnum to get the nth constructor. For example:
nthAuthor :: Int -> Authors
nthAuthor i = toEnum i
>
> main= display Buzzati
> display x = do
> putStrLn (show x)
> display (succ x)
> -- 3 end of enum
To use maxBound you need to make your type an instance of Bounded. You
will also need to make it an instance of Eq in order to compare it.
main= display Buzzati
display x = do
putStrLn (show x)
if x == maxBound
then return ()
else display (succ x)
Patrick
>
> 1. could'nt match expected type [Char] against inferred type Authors
> I would like to display each data constructor name on one line , giving :
> Buzzati
> Werber
> Verne
> How can i translate data from one type to another (Authors to [Char])?
>
> 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
>
> 3. tried to take 'succ' of last tag in enumeration
> How to detect the end of an enumeration ? Can i get the maxbound index ?
>
> Thanks,
> Didier.
>
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
--
=====================
Patrick LeBoutillier
Rosemère, Québec, Canada
More information about the Beginners
mailing list