[Haskell-beginners] User-defined polymorphic data type: heterogeneous list?
Chaddaï Fouché
chaddai.fouche at gmail.com
Mon Jul 11 12:21:14 CEST 2011
On Mon, Jul 11, 2011 at 8:21 AM, Arlen Cuss <celtic at sairyx.org> wrote:
> Hi Christopher,
>
>> As my first stab at it, it seemed like I should be able to create my own
>> heterogeneous "list" data type -- i.e., a "list" data type that can
>> contain elements of different types. (like, [3,'a',True], for example)
>
> One problem I can see would be dealing with the contents of such a list.
> Imagine you have a list with many different types in it. Would every
> type appear in the type of the list? If so, that would have to be a
> consideration before you even get to the "=" sign in your data type
> definition. If not, whence do they come?
That approach can be found in the HList library where indeed the
heterogeneous list at the data level is echoed by an heterogeneous
list at the type level, the basic blocks are :
> data HNil = HNil
> data HCons e l = HCons e l
but with just that you would have no guarantee that the "l" from HCons
was HNil or HCons so you add a typeclass :
> class HList l
> instance HList HNil
> instance (HList l) => HList (HCons e l)
and you don't export the data constructors but smart constructors instead :
> hNil :: HNil
> hNil = HNil
>
> hCons :: (HList l) => e -> l -> HCons e l
> hCons x xs = HCons x xs
And thus you have an heterogeneous list which you can manipulate
usefully, though HList add plenty of stuff to allow cool tricks.
--
Jedaï
More information about the Beginners
mailing list