[Haskell-cafe] List containing different types but all
implementing the same class
Keean Schupke
k.schupke at imperial.ac.uk
Fri Apr 8 12:50:08 EDT 2005
You can do this like:
>data TTrue = TTrue
>data TFalse = TFalse
>
>data Nil = Nil
>data Cons a l = Cons a l
>
>class Constrain c a b | c a -> b where
> constrain :: c -> a -> b
>
>data ZConstraint = ZConstraint
>instance Z a b => Constrain ZConstraint a b
>
>class List c l
>instance List c Nil
>instance (Constrain c a TTrue,List c l) => List c (Cons a l)
Now define a class 'Z' using a fundep such that 'b' becomes TTrue if 'a'
is in Z.
>class Z a b | a -> b where
>instance (TypeEq a Int b,TypeEq a Float b,TOr a b c) => Z a c
> -- Int and Float are members of Z, TypeEq and TOr come from the
> -- HList library.
Finally you can constrain the list:
>f :: List ZConstraint l -> List ZConstraint l
>f x = x
Regards,
Keean.
Bo Herlin wrote:
> Hi everyone. Being new to Haskell I wonder how I can make a list
> contain different types but all implementing the same class, like this:
>
> data X = X
> data Y = Y
>
> class Z a where f :: a -> Int
>
> instance Z X where f x = 0
> instance Z Y where f y = 1
>
> test1 :: Z a => [a]
> test1 = [X,Y]
>
> test2 = map f test1
>
> Is it possible to make this work?
>
> /Bo Herlin
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list