[Haskell-cafe] Named function fields vs. type classes

Keean Schupke k.schupke at imperial.ac.uk
Wed Dec 29 13:34:11 EST 2004

There are two ways to do the list of class members, existentials is one

    data MyBox = forall a . MyClass a => MyBox a
    type MyClassList = [MyBox]

    f :: MyClassList -> MyClassList

An alternative is to use a heterogeneous list (see the HList library):


This allows heterogeneous lists with static typing, which can be
constrained by a class as follows:

class MyClassList x
instance MyClassList HNil
instance (MyClassList l,MyClass v) => MyClassList (HCons v l)

The constraint "MyClassList" now implies a heterogeneous list of members
of "MyClass":

    f :: (MyClassList l,MyClassList l') => l -> l'

This represents a filter function on a heterogeneous list of class 
members - The
drawback is that the list must be statically typecheckable... If you 
require run-time
list construction from IO actions, then you want to use existentials.


Sebastian Sylvan wrote:

>On Tue, 14 Dec 2004 15:40:13 +0000, Keith Wansbrough
><Keith.Wansbrough at cl.cam.ac.uk> wrote:
>>>On the other hand, it's difficult or impossible to make a list of a
>>>bunch of different types of things that have nothing in common save
>>>being members of the class.
>>I've recently been playing with making, for each class C, a
>>"interface" datatype IC (appropriately universally and existentially
>>qualified so as to include a dictionary for class C), and then making
>>this IC an instance of class C.  Then I can wrap any instance of C up
>>in an IC, and make a list of those.
>I think there should be standard syntax for this...
>Some sort of operator for turning one or several type classes into an
>interface datatype.
>So you could write something like something like...
>f :: <Show,Num> -> [<Show,Eq>] -> <Eq,Num> 
>f a xs = ...
>So the first parameter is just a value of the interface datatype
>data ShowNum = forall a . (Show a, Num a)  => ShowNum a
>And it's all automatically up and downcasted.
>This is one of the more powerful idioms in languages such as Java
>(collections of objects which satisfy some interface, for instance)
>and should, IMO, be supported by some special syntax to facilitate
>it's use in Haskell.

More information about the Haskell-Cafe mailing list