[Haskell-cafe] Flags
Donald Bruce Stewart
dons at cse.unsw.edu.au
Thu Aug 10 06:30:56 EDT 2006
Maduser:
>
> I have started to program in Haskell. Now I want programm something like
> flags. It's a set of flags. It sould be possible to convert the Flag as
> Int/String (the bit combination). I have written this:
>
> import Data.Set as Set
>
> type Flags = Set Flag
> data Flag = Flag1 | Flag2 | Flag3
> deriving(Eq, Ord, Enum, Show)
>
> flagToInt :: Flags -> Int
> flagToInt flags = flag1 + flag2 + flag3
> where
> flag1 = if member Flag1 flags then 1 else 0
> flag2 = if member Flag2 flags then 2 else 0
> flag3 = if member Flag3 flags then 4 else 0
>
> but this seems to me to be inelegant. Can somebody help me making it better,
> please.
Something like:
type Flags = [Flag]
data Flag = Flag1 | Flag2 | Flag3
deriving (Eq, Ord, Enum, Show)
flagToInt :: Flags -> Int
flagToInt = sum . map ((2 ^) . fromEnum)
Perhaps?
-- Don
More information about the Haskell-Cafe
mailing list