[Haskell-beginners] Return a Foldable instance

Federico Mastellone fmaste at gmail.com
Wed May 4 20:08:26 CEST 2011


On Wed, May 4, 2011 at 1:22 PM, Chaddaï Fouché <chaddai.fouche at gmail.com> wrote:
> On Wed, May 4, 2011 at 2:21 PM, Federico Mastellone <fmaste at gmail.com> wrote:
>> So, is it even possible to write a function with this type: getValues
>> :: Foldable f => k -> MultiMap k v -> f v ???
>>
>
> It isn't since there's nothing in the Foldable class that allows you
> to build one (only to consume one, do a fold over it, no "unfold").
>

As it's impossible to build a function like this one below:
getValues :: Foldable f => k -> MultiMap k v -> f v
I know that it may be too difficult, but wouldn't be great to make
this type illegal in Haskell ?
You can't make a function that returns a class that has no method that
builds an instance of that class unless another parameter of the
function is of that class or allows you to build one instance of that
class.

> But since this signature is _not_ the one you really want (it says you
> will deliver any Foldable your caller asks for), this isn't a problem,
> what you really want is :
>
>> data ExFoldable a = forall f . (Foldable f) => ExFoldable (f a)

This will do the trick and it is better than maintaining an
intermediate structure as I previously said.
Thank you and Alexander for this tip.

>>
>> instance Foldable ExFoldable where
>>   foldr f z (Exfoldable xs) = foldr f z xs
>>
>> getValues :: k -> MultiMap k v -> Exfoldable v
>> getValues k mm = ExFoldable (yourLookupFunction mm k)
>>
>
> or something like that.
> With this signature you're really saying you will deliver a Foldable
> without telling which one, like in OO.
>
> Now I'm not sure if this is such a good idea since as other have
> pointed, delivering a list is a pretty good and mostly simple option
> where the list itself is often optimized away. But if you really want
> it, Haskell can do it.
>
> (You'll need to activate some extensions to allow this)
>
> --
> Jedaï
>



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