[Haskell-beginners] User-defined polymorphic data type: heterogeneous list?

Mats Rauhala mats.rauhala at gmail.com
Mon Jul 11 07:11:26 CEST 2011


On 21:00 Sun 10 Jul     , Christopher Howard wrote:
> I'm trying to understand parametric polymorphism and polymorphic
> data types. I especially want to go beyond simply using the defined
> polymorphic data types (lists and so forth) and see how I can make
> my own useful ones.
> 
> 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)
> 
> But I'm a little stuck. My first try was like so:
> 
> data HeteroList a b = Null | Element a (HeteroList a b) deriving (Show)
> 
> ...but this of course did not work, because all elements end up
> having to be the same type.
> 
> Then I tried
> 
> data HeteroList a b = Null | Element a (HeteroList b a) deriving (Show)
> 
> ...but this doesn't work because every other other element has to be
> the same type:
> 
> Element 'a' (Element 1 (Element 'a' (Element 2 Null)))
> 
> ...I could go on and embarrass myself some more, but since I'm
> likely widely off-base I'll just ask if somebody can point me in the
> right direction.

I'm not an expert on the subject, but existential quantification allows
it.

{-# LANGUAGE ExistentialQuantification #-}

data HeteroElement = forall a. Element a

list = [Element 1, Element 'a', Element True]

http://en.wikibooks.org/wiki/Haskell/Existentially_quantified_types
http://haskell.org/haskellwiki/Heterogenous_collections

-- 
Mats Rauhala
MasseR
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110711/94495b3f/attachment.pgp>


More information about the Beginners mailing list