简体   繁体   中英

constant variable declaration in Haskell

To declare constant variables I can do following in Ruby

class COLOR
   RED   = 10
   BLUE  = 20
   GREEM = 30
end

COLOR::RED returns 10 , COLOR::BLUE returns 20 , and so on. How do I accomplish that in Haskell?

I want to have a namespace name in front of my variable name. Maybe the example above is not a good example. For the case below, you can see including a namespace name will make a variable much easier to understand.

class BASEBALL_TEAM
   GIANTS = 15
   METS = 30
   REDS = 45
   ...
end

BASEBALL_TEAM::GIANTS is much clear than GIANTS .

based on the comments below, it seems the only way I can accomplish it is by doing something like below:

module Color (Color) where
data Color = Red | Blue | Green deriving (Eq, Show, Ord, Bounded, Enum)                        

fromEnum' x = (fromEnum x) + 10

to get integer value of 10 for Color.Red , I have to write fromEnum Color.Red , the syntax is not very clean.

Untagged constants are bad. If you go with bunch of Int constants then you lose type-checking (think about possible values that Int -> whatever function takes as opposed to SomeConstType -> whatever ) and possibly introduce bugs. You want a strong type instead:

data Colour = Red | Blue | Green deriving (Show, Eq, Enum)

Also, representing those values as integers is not really necessary in most cases. If you actually do need it, Enum typeclass provides toEnum and fromEnum .

As for namespaces: modules are namespaces in Haskell. Put your type in a module and then you can import it qualified and you'll have your prefix:

-- Colours.hs
module Colours (Colour) where
data Colour = ...

-- SomeOtherModule.hs
module SomeOtherModule where
import qualified Colours

foo = Colours.Red

That said, creating modules just for this one type with constants (or importing them qualified) is not really necessary, because you can easily trace things by their types.

Things are constant in Haskell by default, so

red = 10
blue = 20
green = 30

would be equivalent.

A more interesting question would be why you want to do this? There are likely better ways to accomplish what you want in Haskell. The answer by @CatPlusPlus shows a good way of doing this.

This seems like a very basic Haskell question, so I'll politely point you to Learn you a Haskell , which, in my opinion, is the best resource to get started with Haskell.

Another promising resource for learning Haskell is FP complete's School of Haskell , which is currently in beta, but I haven't tried it myself. This is a more interactive setting, where you can directly try things out in the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM