[Haskell-beginners] Multi-param type classes and type dependency

Olivier Iffrig olivier at iffrig.eu
Fri Apr 12 15:57:40 CEST 2013


David McBride wrote (2013-04-12 09:39:59 -0400):
> I don't know if this is the most advisable way to go about things, but if
> you add the FunctionalDependencies extension you can do this:
> 
> class Collection i c => Annotation i c a | a -> c where

Thanks for the advice.

I already tried functional dependencies, but not like that. As far as I
understand how they work, this notation means c is uniquely determined
by a, but I would prefer beign able to handle generic annotation types,
which apply to several collections.

I also came up with a working solution using existential quantification,
but my understanding of it is quite limited so I don't know if it is a
good idea:

data AnyCollection i = forall c. (Collection i c) => Coll c

class Annotation i a where
    collection :: a y -> AnyCollection i -- access the underlying Collection
    select :: a y -> i -> y -- select the annotation of an item given its index

instance Annotation Int (MyAnnotation Things) where
    collection (Ann c _) = Coll c
    select (Ann _ as) i =  as !! i

-- 
Olivier




More information about the Beginners mailing list