[Haskell-beginners] Return a Foldable instance

Antoine Latter aslatter at gmail.com
Wed May 4 06:18:44 CEST 2011


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



More information about the Beginners mailing list