Marshall Multidimensional list, multidimensional array

Peter Simons simons at cryp.to
Wed Nov 10 09:28:52 EST 2004


David Lo writes:

 > [[Int]] to int[][]

Pardon me if I'm telling you something you already know, but I
wanted to make sure you are aware of it.

int[][] is a very different type than [[Int]] is. An int[][]
is a pointer to an array of pointers to integers:

 int[][]  <==>  int*[]  <==>  int**

Now think of the following Haskell list:

 [ [ 1, 2, 3, 4]
 , [ 1 ]
 , [ 1, 2 ]
 ]

C can't easily express that because an array in C does not
have a length -- a list in Haskell, however, does. To
understand the difference, just ask yourself what the element
my_list[1][3] would be. In the Haskell type, this element does
not exist: The second list has only one element. Only, C
doesn't know that! It will simply translate the expression to:

  *( *(my_list + 1) + 3 )

And give you the contents of any random memory location, thus,
almost certainly crashing your program. Which is why C sucks
and Haskell rules. :-)

My point is: marshaling a nested list is really not as simple
as it looks and int[][] is almost certainly not the right type
to marshal to. You'd need something that contains the
information which element list is how long, something like:

  struct integer_list
    {
    size_t  len;
    int*    elements;
    }

  struct nested_list
    {
    size_t         len;
    integer_list*  elements
    }

What _exactly_ you would need, though, is impossible to say
without understanding what you are trying to do. And
explaining all this would probably be too complex to do it
casually on a public mailing list.

I hope this helps somewhat. And I hope I remembered the order
in which C does resolve the int[][] type correctly. I could
never get that right. I hope someone corrects me, should it be
wrong.

Peter



More information about the Glasgow-haskell-users mailing list