[Haskell] concurrent haskell, higher-order types and parameterizing by typeclass

Abraham Egnor abe.egnor at gmail.com
Tue Apr 13 11:35:26 EDT 2004


I have a system composed of threads communicating via channels; I'd
like the communicated types to be instances of a particular typeclass
(say Show for purposes of discussion), but not all the same type. 
Since Chan is paramterized by the communicated datatype, the best way
I've found to do this is via a wrapper type:

data Showable = forall a. Show a => Showable a

writer :: Chan Showable -> IO ()
writer ch = mapM_ (writeChan ch) [Showable 42, Showable pi, Showable
"hello", Showable 'c']

printer :: Chan Showable -> IO ()
printer ch = getChanContents ch >>= mapM_ (\(Showable a) -> print a)

However, this solution requires a new wrapper datatype (or at least a
new constructor) to be defined for every typeclass to be used in
Chan-based communication; furthermore, all of the datatypes will be
identical except for the name of the typeclass.  It seems like I
should be able to create a type that's parameterized by typeclass,
i.e. something like:

data Wrapper c = forall a. c a => Wrapper a

writer :: Chan (Wrapper Show) -> IO ()
...

Alternatively, are there any ideas as to how I could communicate
heterogeneous instances of a given typeclass in a typesafe manner
(i.e. without escaping to Data.Dynamic)?

Abe


More information about the Haskell mailing list