The Array Type
In most programming languages, we have arrays that can store whatever type of
values we want, but the array elements are indexed using integer values starting
at 0 for the first array element. Haskell arrays are more general. We can use
any type in the Ix
type class as array indices. Roughly speaking, those are
types for which we know how to convert values into 0-based integer indices. So,
under the hood, Haskell arrays are also indexed using integer values starting at
0—what other choice is there really, given that our computer's memory is a
linear array of memory cells—but as a convenience, they support conversion from
fairly arbitrary index types to these 0-based integer indices.1
An array in Haskell is parameterized by two types. An array of type
Array i e
stores elements of type e
and uses values of type i
as array
indexes. We can use characters, Booleans, Integers or tuples of integers as
array indexes. The latter is useful for implementing what is logically a
higher-dimensional array. To show you examples of arrays, I first need to
explain to you how to construct arrays.
-
This conversion comes at a price, and arrays aren't all that fast to manipulate in Haskell, exactly because every access to an array element involves a conversion between logical array indices and the actual 0-based integer indices used under the hood. As a result, performance-critical code often uses the
Vector
type from thevector
package instead of arrays. Vectors only support 0-based integer indexes and thus save the cost of index translation. ↩