[Haskell-cafe] Collection of objects?

Steve Schafer steve at fenestra.com
Fri Nov 17 14:04:22 EST 2006

On Fri, 17 Nov 2006 18:36:30 +0100, you wrote:

>But I need something which is heterogeneous and non-fixed length. I'm 
>used do Java, and this switch to functional languages is very strange to 
>me. So, to be clear, I need something like LinkedList<Object> in java.

In an attempt to leverage your existing Java knowledge...

In Java, while the "things" in your list are heterogeneous at some
level, they are homogeneous at another: They are all instances of Object
(or a subclass thereof). You can't, for example, put an int in your
list. And in fact, that's a primary reason for the existence of the
Integer class--it makes your int look like an Object, so that you can
treat it like one. (And similarly for Character, Float, Double, etc.)

So you do the analogous thing in Haskell: First, you ask yourself, "What
kinds of things do I want to put in my list?" Once you have the answer
to that, you ask, "Are these things homogeneous at some level?" If they
are, then you make your list a list of those homogenous things
(actually, the compiler generally does it for you). If they aren't, then
you wrap them up in a homogeneous wrapper in exactly the same way as you
wrap your int in an Integer, your double in a Double, etc., in Java.

Some of the other replies have shown you how to declare this; it's
trivially simple:

 data MyHomogeneousWrapper = Integer Int
                           | Character Char
                           | Float Float
        deriving Show

Finally, constructing new instances of this homogenous wrapper in
Haskesll is just like it is in Java:

 myList = [(Integer 42), (Character 'a'), (Float 3.14159)]


 myList = new LinkedList();
 myList.add(new Integer(42));
 myList.add(new Character('a'));
 myList.add(new Float(3.14159));

Steve Schafer
Fenestra Technologies Corp.

More information about the Haskell-Cafe mailing list