[Haskell-beginners] constant set
Ovidiu Deac
ovidiudeac at gmail.com
Sat Mar 10 15:45:27 CET 2012
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
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120310/eed0fe7e/attachment.htm>
More information about the Beginners
mailing list