[Haskell-cafe] Implementing and indexing 2 dimen arrays

Alastair Reid alastair at reid-consulting-uk.ltd.uk
Thu Mar 25 22:40:37 EST 2004


> I'd like to know how to index a particular element at run-time
> as I don't know on which element of which sublist I am at the moment
> in pullHelper function which starts with values !! ind p xs !!

It's maybe worth pointing out that few Haskell programs use indexing.  It's 
far more common to see programs use pattern matching, array comprehensions,  
or a higher order function than to see indexing of lists.  For example, I'd 
write:

  map show xs

instead of

  [ show (xs !! i) | i <- [0..length xs -1]

  (which is about the closest translation of a C
   for loop indexing an array).

or, if you need the index of a value in an array, you might write something 
like:

  [ i*x | (i,x) <- zip [0..] xs ]

Not only is is usually shorter to avoid indexing but it is also less error 
prone.  In C, Pascal, etc. it is really easy to walk off the end of an array 
and the error isn't caught until (at best) runtime.  If you use pattern 
matching, etc. the error is harder to make and tends to be caught at compile 
time.

Of course, sometimes you do need random access.  For that, you should use 
arrays.

--
Alastair Reid        www.haskell-consulting.com


More information about the Haskell-Cafe mailing list