Re: What is a Haskell way to implement flags?
Ertugrul Söylemez <es <at> ertes.de>
2013-02-19 23:39:32 GMT
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
data Options =
_optFiles :: Set FilePath,
_optFlags :: Set Flag
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. =)
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.
Haskell-Cafe mailing list
Haskell-Cafe <at> haskell.org