[Haskell-beginners] Return a Foldable instance

Chaddaï Fouché chaddai.fouche at gmail.com
Wed May 4 07:51:48 CEST 2011


On Wed, May 4, 2011 at 7:18 AM, Federico Mastellone <fmaste at gmail.com> wrote:
> Yes, I got confused between haskell type classes and OO classes.
>
> 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.
>
> One implementation returns a list and the other a set, both Foldables.
> But I can't make a function like the one below for this two
> getValues :: Foldable f => MultiMap k v -> f v
>

Writing this function given your intention (doing different thing
depending on the type) is equivalent to writing an instance of
Foldable for your (MultiMap k). If the underlying structure of your
multimaps is always foldable, it doesn't make sense to make a function
like this, the multimaps themselves should be Foldable. This is not
hard to do, refer to the doc (
http://www.haskell.org/ghc/docs/7.0-latest/html/libraries/base-4.3.1.0/Data-Foldable.html
) to see how to write a minimal instance of Foldable.

-- 
Jedaï



More information about the Beginners mailing list