We covered plenty of functions from the
List module, but we didn’t get to one of the most common operations performed on a list: accessing elements by index. That’s because there is no easy way to do that with lists. Because of the way lists are implemented, they are easy to traverse linearly, but accessing an element in random order is expensive. For example, to get to the last element in the list shown below, we have to first traverse through the six elements before it which is inefficient. We can imagine how inefficient it will get when a list has thousands of elements in it.
Not to worry — Elm offers another data structure called Array that makes accessing a random element a breeze. Arrays are very similar to lists in behavior. Almost any operation that can be performed on a list can be performed on an array too.
Creating an Array
Unfortunately, we can’t create an array with a literal syntax like list. The most common way to create an array is to first create a list and then transform it to an array.
Array module is included in Elm Platform, it isn’t automatically loaded by
elm repl. Therefore, we need to import it explicitly.
fromList is a function that takes a list and creates an array from it. Notice when we printed the value of
myArray constant, the repl gave us
Array.fromList [1,2,3,4] as the output? That whole output is what represents the array.
[1,2,3,4] by itself is still just a list.
We can also transform an array to a list.
If we want to include the index of each element when we transform an array to a list, we can do that too using the
Sometimes we need to initialize each element of an array with some value. We can use the
initialize function for that. The example below creates a list with all elements initialized to zero.
initialize takes two parameters:
- Length of an array.
- Function for generating each element.
initializepasses the index of an element as an argument to this function.
We used the
always function (also defined in the
Basics module) to return
0 for each element.
always is defined like this:
It’s a constant function that ignores the second argument and always returns the first argument.
- Constant Function
- A constant function in mathematics is a function whose output is the same for every input value.
Another way to initialize an array with the same value is to use the
Basics module also provides a function called
identity that, unlike
always, returns the given value. Let’s use this function to create an array whose elements and the indexes are exactly the same.
identity is not a constant function — its output depends on what the input is. Here’s how
identity is defined in the
Getting and Setting a Value
To retrieve a specific element from an array, all we have to do is specify its index and the
get function will return that element for us.
get returns an element wrapped inside
Just. We saw a similar example when we asked a list to return its head. We will learn how to unwrap a value from
Just in chapter 4. Let’s see What happens if we try to access an index that doesn’t exist.
Instead of an error, we get
Nothing which makes perfect sense. Similarly, we can set an element at a particular index by using the
set takes three arguments:
- The index of the element we want to update
- The new value that’ll replace the existing element
- An array
It’s important to know that
set returns a new array instead of modifying an existing array. If we print the contents of
myArray, we will see that it hasn’t been changed at all.
This behavior is consistent with all other operations. It doesn’t matter which data structure we are dealing with, Elm never mutates them. We will discuss immutability in much more detail in chapter 4.
isEmpty function determines whether or not an array is empty whereas
length returns the number of elements in an array.
length functions in array work exactly the same way as in list.
append function combines two arrays.
We cannot, however, use the
++ operator to append two arrays.
If we want to add an element to the end of an array, we can do that too with the
There is no function to add an element to the beginning of an array. That’s because it’s an expensive operation. Each element has to be moved one step right and if an array has lots of elements in it, it could get quite slow from performance standpoint. But adding an element to the end of an array is quite cheap because it doesn’t require other elements to move.
We can get around the performance issues caused by adding an element to the beginning of an array by appending that element instead.
Remember how we extracted a substring earlier in this chapter by using the
Array module also provides a function called
slice that extracts a sub-section of an array. Like
String.slice, it also takes three arguments:
- Index where the sub-array starts
- Index where the sub-array ends
- An array
Array.slice both extract elements up to but not including the end index. We can also use negative indices with
Notice how we popped off the last element from
myArray by using a negative index. Nice trick, huh?
Mapping, Filtering, and Folding an Array
Earlier in the List section, we took a closer look at how map, filter, and fold operations work. Their behavior is exactly the same in an array too. Let’s see some examples.
Folding from left
Folding from right
List vs Array
Now that we know what lists and arrays are, we are left with an important question: which one should we use and when? As lists have no easy way to access an element by index, we have no choice but to use arrays when we need positional access. But in all other cases, I recommend using lists because they are the standard choice for representing a sequence of values in Elm.
Furthermore, creating a list is easy with literal square brackets, whereas creating an array is somewhat cumbersome. We have to first create a list and then use the
fromList function to convert that list to an array.