[Haskell-beginners] Return a Foldable instance

Federico Mastellone fmaste at gmail.com
Wed May 4 08:25:32 CEST 2011


On Wed, May 4, 2011 at 2:36 AM, Brent Yorgey <byorgey at seas.upenn.edu> wrote:
> 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.

I want a function that returns the best way to traverse, fold, fmap,
etc a part of the multimap without making any mention to the
underlying structure. That would be instances of Functor, Foldable or
Traversable.

>
> 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.

Because the underlying structure is already Foldable, so why creating
a dummy function for every method on the Foldable class that only
calls the same function but in the underlying structure. I return a
Foldable and the user can foldr1, foldl1, etc.

>
> -Brent
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>



-- 
Federico Mastellone
Computer Science Engineer - ITBA
".. there are two ways of constructing a software design: One way is
to make it so simple that there are obviously no deficiencies, and the
other way is to make it so complicated that there are no obvious
deficiencies. The first method is far more difficult."

Tony Hoare, 1980 ACM Turing Award Lecture.



More information about the Beginners mailing list