views:

267

answers:

3

Say I have a list of numbers from 1 to MAGIC_NUMBER -- Is there a way I can declare this beforehand ?

+6  A: 

You can use algebraic data in all your calculations and use some named values if they are really "magic", or build render of algebraic values to "magic" numbers and many more:

class FlagsMask f where mask :: f -> Int

data Magics = Alpha | Beta | Gamma
    deriving (Enum, Read, Show, Eq, Ord)

instance FlagsMask Magics where
    mask m = 2 ^ fromEnum m

data PermsFlag = FlagRead | FlagWrite | FlagExec | FlagSuper

-- [flagRead, flagWrite, flagExec] = [2^n | n <- [0..2]]
(flagRead : flagWrite : flagExec : _) = [2^n | n <- [0..]]
flagSuper = 16

instance FlagsMask PermsFlag  where
    mask FlagRead = flagRead
    mask FlagWrite = flagWrite
    mask FlagExec = flagExec
    mask FlagSuper = flagSuper
*Main> map fromEnum [Alpha .. ]
[0,1,2]
it :: [Int]
*Main> zip [Alpha .. ] [1..]
[(Alpha,1),(Beta,2),(Gamma,3)]
it :: [(Magics, Integer)]

ony
+14  A: 

Sure. In fact, given that Haskell is purely functional, it's much easier to define a constant than a non-constant.

magicNumber = 42

magicList = [1..magicNumber]
Chuck
+10  A: 

Chuck's and ony's answers are correct. There's one trap you should be aware of:

magicNum = 42

f magicNum = 'A'
f _ = 'B'

is NOT what you might expect - magicNum in second line is a pattern that matches everything, just like f x = 'A'. Use f x | x == magicNum = 'A'.

sdcvvc