Arrays in Haskell
Our first program will demonstrate how to work with arrays in Haskell. Here’s the full source code and explanation:
In Haskell, arrays are not as commonly used as lists, but they are available through the Data.Array
module. Here’s a breakdown of the code:
We import the
Data.Array
module to work with arrays.We create an array
a
with 5 elements, all initialized to 0. In Haskell, arrays are created with a specified range and a list of index-value pairs.We can set a value at an index using the
//
operator, which creates a new array with the updated value.To get a value from an array, we use the
!
operator.The length of an array can be obtained by using
rangeSize
on the bounds of the array.We can create and initialize an array in one line using list comprehension.
The
listArray
function allows us to create an array from a list of values.We can create an array with some elements specified and others defaulting to 0 by only providing the non-zero elements.
Multidimensional arrays are created by using tuples as indices.
We can also create and initialize multidimensional arrays at once using
listArray
.
When you run this program, you’ll see output similar to this:
Note that Haskell arrays are immutable, so operations that seem to modify an array actually create a new array. This is different from many other languages where arrays are mutable.