[Haskell-beginners] constant set

Lyndon Maydwell maydwell at gmail.com
Sat Mar 10 15:56:03 CET 2012


If you simply want color names to correspond to Ints, you can just
define them at the top level:

> red = 1
> blue = 2
> green = 3

What are you trying to gain here by having the color namespace?

2012/3/10 Ovidiu Deac <ovidiudeac at gmail.com>:
> Thanks for the answers. I guess my example with the colors was misleading.
> In that case it makes sense to use an abstract type.
>
> In my case an abstract type is not ok. What I want is a set of int constants
> i.e. some names for some ints that I will use in my code, to avoid magic
> numbers in the code.
>
> Of course I could define them like this:
> red = 1
> blue = 2
>
> ...but that would pollute the namespace
>
> Also I don't want to define them in a separate file. I would like to define
> them in the same file where I use them.
>
> I already tried this approach:
>
> module Main where
>
> import ....
>
> module Colors where
>   red = 1
>   blue = 2
> .....
>
> but the compiler complains at the line "module Colors where". It says: parse
> error on input `module'
>
>
>> 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/
>>
>> _______________________________________________
>> Beginners mailing list
>> Beginners at haskell.org
>> http://www.haskell.org/mailman/listinfo/beginners
>>
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>



More information about the Beginners mailing list