bool-extras: A fold function for Bool

Haskell’s boolean type is regarded differently from other data types such as Maybe or Either. Both those types have a ‘fold’ function defined for them (maybe and either, respectively), but Bool doesn’t have such a function. All Bool is stuck with is the build-in if then else-syntax, or worse: pattern matching.

With a ‘fold’ function (also known as a reducer, eliminator or catamorphism) you can reduce a value of one data type to a value of another data type. This is a very popular way to reduce values, e.g. lists have the very popular foldr. This package provides that same function for the Bool data type; a function called bool!

The bool function

The bool function is a replacement for the build-in if then else-syntax. However, since it is a function instead of syntax, it can be partially applied and passed around to higher order functions, like so:

ghci> :m + Data.Bool.Extras
ghci> let yesOrNo = bool "no" "yes"
ghci> map yesOrNo [True, False, True]
["yes", "no", "yes"]

Note that the arguments to bool are in the opposite order of the if then else-syntax; First the false value, then the true value, and finally the boolean. This argument order is consistent with the data type declaration and functions like maybe.

Other functions

The package contains some other functions that are mostly just partial applications of the bool function.

There is the mwhen for Monoids, whenA for Arrows, and whenM for Monads. These are useful when you either want to do something, or not and take the default route. Here’s an example of mwhen for Monoids:

-- Important numbers!
xs = [6, 9, 13, 42]

-- Without library
f :: Bool -> [Int]
f b = if b then xs else []

-- With library
g :: Bool -> [Int]
g = mwhen xs

See? It’s an amazing 14 characters shorter!

Installing bool-extras

The current version of bool-extras is 0.3.0 and is available on Hackage.

If you have cabal-install (which you really should have, by the way), the package can be installed like so:

cabal update
cabal install bool-extras

If you don’t have cabal-install, you can manually download and install bool-extras:

wget http://hackage.haskell.org/packages/archive/bool-extras/0.3.0/bool-extras-0.3.0.tar.gz
tar xzf bool-extras-0.3.0.tgz
cd bool-extras-0.3.0
./Setup.lhs configure --user
./Setup.lhs build
./Setup.lhs install

About the package

The source code for this packages lives in a public git repository on github.

The co-authors for this library are: Erik Hesselink, Jeroen Leeuwestein, and Sebastiaan Visser
(by “co-authors”, I of course mean: people who couldn’t stop laughing when I wrote the library).

Releases

0.3.0

  • Added the mwhenM function, requested by Sebastiaan Visser.
  • Added upper bound for base in .cabal file.
  • Cleaned up documentation and code.

0.2.0

  • Initial public release.