[Haskell-cafe] Could someone teach me why we use Data.Monoid?

Duncan Coutts duncan.coutts at googlemail.com
Fri Nov 13 17:20:45 EST 2009


On Fri, 2009-11-13 at 15:16 -0200, Rafael Gustavo da Cunha Pereira Pinto
wrote:
> 
> "...in my humble opinion. (Which, obviously, nobody else will agree
> with.)"
> 
> I somewhat agree with your opinion!!
> 
> What I miss the most is practical examples:
> 
> 1) A function that uses a Monoid as a container
> 2) A function that uses Monoid as algebra
> 
> and so on, for most of categories.

Here are two practical examples.

Most aggregate statistic functions (think of all the aggregate functions
in SQL, sum, average, stddev) are monoids. So you can write a generic
"compute statistics" function for some dataset and then use it for any
monoid statistic function that you come up with. Even better, your
"compute statistics" function can take advantage of parallelism since
the monoid operation is associative.

Another practical example is config files and (equivalently) sets of
command line flags. These things are records containing fields. But each
field is a monoid (usually list or last) and this lets you make the
whole record a monoid, point wise. This lets you do useful stuff like
combining configuration from multiple sources (like a config file,
defaults and command line) using just mappend.

Now you could say, why make it a monoid, why not just provide a function
`combineStats` or `combineConfig`. There are two reasons, one is that it
provides documentation, it says "this thing is an instance of that
well-known pattern". Secondly it sometimes lets you reuse generic
functions (eg Data.Traversable).

Duncan



More information about the Haskell-Cafe mailing list