[Haskell-beginners] constant set

Ertugrul Söylemez es at ertes.de
Sat Mar 10 02:04:08 CET 2012


Ovidiu Deac <ovidiudeac at gmail.com> wrote:

> If I want to define a constant set in Python I would do this:
> class Colors:
>   red = 1
>   blue=2
> ...
>
> and then I use them like this: Colors.red, Colors.blue...
>
> Can I do something similar in Haskell?

In Haskell this would usually be an abstract type:

    data Color = Red | Blue | ...

You could then use functions to convert between integers and colors.

    fromColor :: Color -> Int
    toColor   :: Int -> Maybe Color

You could also derive an Enum instance and get the conversion functions
'fromEnum' and 'toEnum' for free, although in that case the 'toEnum'
function is less safe (no Maybe):

    data Color = Red | Blue | ...
                 deriving Enum

    fromEnum :: Color -> Int
    toEnum   :: Int -> Color


Greets,
Ertugrul

-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120310/2126ace7/attachment.pgp>


More information about the Beginners mailing list