[Haskell-beginners] Return a Foldable instance

Brent Yorgey byorgey at seas.upenn.edu
Wed May 4 07:36:51 CEST 2011


On Wed, May 04, 2011 at 02:18:14AM -0300, Federico Mastellone wrote:
> I want to create different implementations of a multimap, for example
> using lists and using Data.Set, and instead of providing functions
> getValuesList and getValuesSet that return a [] and a Set respectively
> I want to provide a more generic one, getValues that returns a
> Foldable and avoid unnecessary conversions to and from lists. This way
> the user folds directly the underlying structure, without having to
> worry about which function is the best to fold the values. But I don't
> know how to do this without an extra intermediate data type.

A couple thoughts:

First, I am not sure why you are so worried about avoiding an
intermediate list.  It smells like premature optimization to me.  I
doubt it will really make that big of a difference; and depending on
how the result is used, the intermediate list might be optimized away
anyway.

Second, if you really want to *only* allow the caller of getValues to
be able to fold the result, then you can just "inline" the fold, like
so:

  getValues :: Monoid m => MultiMap k v -> (v -> m) -> m

That is, instead of getting a Foldable thing and doing the fold
themselves, they provide a mapping from values to some monoid and you
do the fold for them.

-Brent



More information about the Beginners mailing list