[Haskell-cafe] What is a Haskell way to implement flags?

Ertugrul Söylemez es at ertes.de
Wed Feb 20 00:39:32 CET 2013


Brandon Allbery <allbery.b at gmail.com> wrote:

> > In C usual way is to set some bit in integer variable by shifting or
> > oring, and than check flag integer variable by anding with
> > particular flag value. What is Haskell way?
>
> You can do that, but a somewhat more idiomatic way would be a list
> (or, slightly less conveniently but more accurately, a Data.Set) of
> constructors from a flags ADT.

The Set way is the one I would prefer.  In fact together with lenses you
even get the boolean interface and a nice interface in general.  Define
your option types:

    data Flag =
        Debug | Verbose
        deriving (Ord)

    data Options =
        Options {
          _optFiles :: Set FilePath,
          _optFlags :: Set Flag
        }

    makeLenses ''Options

The fun starts when you have a state monad around Options, because then
you can use lenses very easily.  Let's add a file:

    optFiles . contains "blah.txt" .= True

Let's set the Verbose flag:

    optFlags . contains Verbose .= True

Let's flip the Verbose flag:

    optFlags . contains Verbose %= not

Are we verbose?

    verbose <- use (optFlags . contains Verbose)

Have fun. =)


Greets,
Ertugrul

-- 
Not to be or to be and (not to be or to be and (not to be or to be and
(not to be or to be and ... that is the list monad.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20130220/8e271da7/attachment.pgp>


More information about the Haskell-Cafe mailing list