List containing different types but all implementing the same class

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

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@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe

On Fri, 8 Apr 2005, Bo Herlin wrote: (snip)
Is it possible to make this work?
This is an extension beyond the 1998 standard, but http://haskell.org/hawiki/ExistentialTypes may be interesting to you. -- Mark

Mark Carroll wrote:
On Fri, 8 Apr 2005, Bo Herlin wrote: (snip)
Is it possible to make this work?
This is an extension beyond the 1998 standard, but http://haskell.org/hawiki/ExistentialTypes may be interesting to you.
Yes, I think this is what I was aiming at. Thanks! /Bo Herlin
participants (3)
-
Bo Herlin
-
Keean Schupke
-
Mark Carroll