Conversion to a List
array
and listArray
allow us to build an array from a list. It can also be
useful to convert an array back to a list. This comes in three flavour:
indices
We may be interested in only the array indices. For this, we have
indices :: Ix i => Array i e -> [i]
>>> arr = listArray (1,26) ['A'..'Z']
>>> indices arr
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
If we don't need the whole list of indices and only need a pair consisting of
the minimum index and maximum index, as provided as the first argument to
array
or listArray
, we also have the bounds
function:
>>> bounds arr
(1,26)
elems
Most of the time, we don't just want the array indices but the array elements or the index-element pairs of the array. We retrieve the list of elements in the array in order of increasing indices using
elems :: Array i e -> [e]
>>> elems arr
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
In this example, the result is a list of characters, which GHCi formats as a string.
assocs
To access the list of index-element pairs, again in order of increasing indices, we use
assocs :: Ix i => Array i e => [(i, e)]
>>> assocs arr
[(1,'A'),(2,'B'),(3,'C'),(4,'D'),(5,'E'),(6,'F'),(7,'G'),(8,'H'),(9,'I'),(10,'J'),(11,'K'),
(12,'L'),(13,'M'),(14,'N'),(15,'O'),(16,'P'),(17,'Q'),(18,'R'),(19,'S'),(20,'T'),(21,'U'),
(22,'V'),(23,'W'),(24,'X'),(25,'Y'),(26,'Z')]