[Haskell-beginners] Enumerated types
legajid
legajid at free.fr
Sun Dec 27 12:17:34 EST 2009
Thanks.
for 1, i tried mapM ( putStrLn) (show pref) but show gives only one
line with all values, instead of n lines with 1 value. I now understand
that show must be in the function that is mapped.
for 2, ok
for 3, ok with new classes in deriving. I thought that i would have to
write new instances of Bounded or Eq, but now i think it's unuseful
since standard functions exist in these classes.
Patrick LeBoutillier a écrit :
> 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
>>
>>
>
>
>
>
More information about the Beginners
mailing list