[Haskell-beginners] Return a Foldable instance

Federico Mastellone fmaste at gmail.com
Wed May 4 07:18:14 CEST 2011


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

On Wed, May 4, 2011 at 1:18 AM, Antoine Latter <aslatter at gmail.com> wrote:
> On Tue, May 3, 2011 at 11:08 PM, Federico Mastellone <fmaste at gmail.com> wrote:
>> Thank you both!
>>
>> So, how can I return something that implements Foldable, so the caller
>> can fold without knowing if it is a [] or a Set and also be able to
>> change the underlying implementation without breaking the code?
>>
>
> Well again, this is not what typeclasses are - in spite of the name,
> they are nothing like OO-style classes.
>
> If you want to hide your implementation, then (as you suggest bellow)
> you need to create a new type and not expose the details of the type.
> If you want the caller to be able to use the 'Foldable' family of
> functions then your new type needs to implement the 'Foldable'
> typeclass (or export equivalent functionality in some other way.)
>
>> With this I also want to avoid the extra overhead of the conversion to
>> or from lists, so the user will be folding the [] or Set directly,
>> depending on the implementation.
>>
>> Creating an intermediate data type like this:
>> Temp a = TempList [a] | TempSet (Set a) | ...
>> That implements Foldable could be one solution, but is it a good one?
>
>> A cons of this is that every new implementation will have to alter
>> this type as well as creating the implementation.
>
> I really don't know enough about what you're trying to do to answer
> this - going with our current example the value:
>
>> test :: SomeType Int
>
> only has one implementation.
>
> Feel free to respond back with more details about your problem.
>
> Antoine
>



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