[Haskell-cafe] Comments from OCaml Hacker Brian Hurt

Jonathan Cast jonathanccast at fastmail.fm
Sun Jan 18 00:55:43 EST 2009

On Sat, 2009-01-17 at 10:47 +0100, david48 wrote:
> On Fri, Jan 16, 2009 at 4:04 PM, Jonathan Cast
> <jonathanccast at fastmail.fm> wrote:
> > On Fri, 2009-01-16 at 14:16 +0100, david48 wrote:
> >> Part of the problem is that something like a monoid is so general that
> >> I can't wrap my head around why going so far in the abstraction.
> >> For example, the writer monad works with a monoid; using the writer
> >> monad with strings makes sense because the mappend operation for lists
> >> is (++), now why should I care that I can use the writer monad with
> >> numbers
> >> which it will sum ?
> >
> > To accumulate a running count, maybe?  A fairly common pattern for
> > counting in imperative languages is
> >
> > int i = 0;
> > while (<get a value>) i+= <count of something in value>
> >
> > Using the writer monad, this turns into
> >
> > execWriter $ mapM_ (write . countFunction) $ getValues
> well thank you for the example, if I may ask something: why would I
> need to write a running count this way instead of, for example, a non
> monadic fold, which would probably result in clearer and faster code
> (IMHO) ?

I agree with you, for this special case.  (Did I remember to post the
simpler solution:

  sum $ map countFunction $ getValues

somewhere in this thread?)

But, just like the (utterly useless) C++ example translated to Haskell
in another thread, the monadic form provides a framework you can fill
out with larger code fragments.  So if the while loop above was replaced
with a larger control structure, maybe recursion over a custom tree
type, then standard recusion operators, such as folds, may be
inapplicable.  In that case, moving to a Writer monad can get you some
of the advantage back, so you don't end up passing your accumulator
around everywhere by hand.


More information about the Haskell-Cafe mailing list