Not logged in. Login

Arrays in Haskell

Haskell supports arrays as well as lists. Both are containers of elements all of the same type, with a defined ordering of elements. However, arrays are fixed in size and support efficient random access to array elements.

Import the Library

To use Haskell arrays, you first need to import the relevant library.

import Data.Array

Creating Arrays

Arrays are conveniently created in two ways.

  • Given a list of all the elements of an array, in order, an array can be constructed using the listArray operation.
    • The first argument to listArray is a pair indicating the bounds of the array for indexing.
    • The second argument is a list with the values of all list elements given individually.

listArray (0, 7) [1, 7, 0, 6, 0, 4, 0, 0]

  • An array can also be constructed using a list of mappings of (index, value) pairs.
    • For example, we can construct a table of squares of the integers from l to 8.

array (1, 8) [(i, i * i) | i <- [1..8]]

Accessing Elements

Array elements are accessed using the ! infix operator. Thus a!3 accesses the array element with index 3.

Multidimensional Arrays

Multidimensional arrays can easily be created by using pairs of coordinates for the range bounds.

For example, a 4x4 multiplication table can be created as follows.

array ((1,1), (4,4)) [((i,j), i*j) | i <-[1..4], j <- [1..4]]

Immutability

Haskell arrays, like all data objects are immutable. So one cannot change an element in an existing array.

However, it is possible to create a new array that is the same as an existing element with certain elements changed. The // operator is used for this purpose.

For example, produce an array a1 based on array a0 but with the diagonal elements replaced by 0.

a1 = a0//[((i,i), 0) | i <- [1..n]]

Both a0 and a1 are immutable objects. However, if the Haskell compiler can determine that a0 is no longer needed, it may optimize the implementation avoid creating a copy.

Updated Thu Sept. 20 2018, 12:08 by cameron.