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

David McBride dmcbride at neondsl.com
Mon Jul 11 07:22:13 CEST 2011


There are two main ways to get lists with different types.

Method one is the most common.

data MyTypes = MyInt Int | MyString String

--Then in your code you deal with it like so:
blah = map myTypeFunc [MyInt 1, MyString "asdf"]
  where
    myTypeFunc :: MyTypes -> IO ()
    myTypeFunc (MyInt i) = putStrLn $ show i
    myTypeFunc (MyString s) = putStrLn s

You can even use parametric types to make it more general

data MyTypes a b c = Type1 a | Type2 b | Type3 c

But you are still going to have to deal with each type explicitly
every function that handles them.

The other way is to use type classes:

class MyClass where
  somefunction :: Bool -> a

instance MyClass Int where
  somefunction True = 1
  somefunction False = 0

instance MyClass String where
  somefunction True = "true"
  somefunction False = "false"

Then you make functions that ultimately make use of only the class's
functions.  Since it is the only property on every element of the list
that is guaranteed to be there, it is all you can use.

myList :: MyClass a => [a]
myList = [somefunction True, somefunction False]

There are cases where one is the better option and cases where the
other is best.

Adapting this to your custom lists, you'd make a datatype like:

data HeteroList = Null | Element MyType HeteroList

On Mon, Jul 11, 2011 at 1:00 AM, Christopher Howard
<christopher.howard at frigidcode.com> 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.
>
> --
> frigidcode.com
> theologia.indicium.us
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>



More information about the Beginners mailing list