[Haskell-cafe] Enum instantiation

Gregory Collins greg at gregorycollins.net
Fri May 21 21:53:54 EDT 2010


R J <rj248842 at hotmail.com> writes:

> I'd like to make "Day" an instance of class "Enum," but the definition
> of toEnum below seems to be completely wrong, because integers seem
> not permit pattern matching.  How is toEnum defined?  Thanks.

You could try using guards:

>     toEnum x | x == 0    = Sunday
>              | x == 1    = Monday
>              | x == 2    = Tuesday
>              | x == 3    = Wednesday
>              | x == 4    = Thursday
>              | x == 5    = Friday
>              | x == 6    = Saturday
>              | otherwise = error "bad enum"

BTW if none of your constructors have fields you can just add Enum to
the "deriving (...)" list for your type, and the compiler will write
basically the same instance for you.

G.
-- 
Gregory Collins <greg at gregorycollins.net>


More information about the Haskell-Cafe mailing list