Tutorial :How do I use constants in haskell, to avoid magic numbers?



Question:

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


Solution:1

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]  


Solution:2

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'.


Solution:3

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)]    

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »