Lists and Tuples
Lists
Collection of objects in Linked list O(n)
Here is an example of a list in Elixir: [1, 2, 3, 4]
This may look exactly like an array if you are familiar with Ruby or Javascript, however they’re a little different in the details. We’ll get into that later.
Lists in Elixir are created by surrounding a list of values with brackets []
. Try creating a list in the console by typing [1, 2, 3]
.
Lists don’t need to contain only one type. They can hold on to multiple different types in the same list.
[1, 2, 3]
["a", "b", "c"]
[1, :b, "c", "c"]
We create the list with the brackets, and by typing literal values into the items; you can also use variables in lists.
Type the following:
iex> foo = "bar"
"bar"
iex> [1, foo, 3]
[1, "bar", 3]
As you can see, Elixir replaces the variable with the literal value in the list it creates.
We have a bunch of built-in methods we can use to interact with and manipulate lists in Elixir.
HEAD/TAIL
We often will want to figure out the first item in a list
[h | tail] = [1, 2, 3]
Notice we have a list with two variables on the left. The h
variable will match to the first value on the right. tail
will hold the rest of the values in the list.
Try typing the following into the command line:
[h | tail] = [1, 2, 3]
now type in h
you should see:
iex> h
1
If we type in tail
- we should see the rest of the list.
iex> tail
[2, 3]
List Concatenation
Try adding and removing items from lists.
Adding lists
To concantenate list we use the ++
operator.
[1] ++ [2] # [1, 2]
Type the following:
iex> [1] ++ [2] # [1, 2]
Subtracting Lists
Let’s take a look
[1, 2, 3] – [2] # [1, 3]
If we have duplicate values we want to remove like so:
It will only remove one of the duplicates
[1, 2, 2, 2] -- [2]
Tuples
Tuples in Elixir are datatypes similar to lists. But they are used to store a fixed number of elements. Let’s look at how to create a tuple.
Tuples are created by using the curly brackets with elements separated by commas.
Type the following into the console:
iex> {:ok, "hello"}
If we want to retrieve the first element in the tuple which is located at index 0, we can pass the index into the function below.
Type the following into the console:
iex> elem({:ok, "hello"}, 0)
:ok
As you can see, the function returns :ok
.
We can check the size of a tuple using the tuple_size/1
function:
Type the following:
iex> tuple_size({:ok, "hello"})
2
And we can replace elements in a tuple by using the put_elem/3
function, which takes the tuple, the argument, and the value:
Type the following:
iex> put_elem({:ok, "hello"}, 1, "world")
{:ok, "world"}
Tuples vs Lists?
- Lists are slow to modify/read, but fast creation
- Tuples are expensive to modify but good for pattern matching and additional information
Next step:
Go on to Keyword Lists.
Or:
Go back to Operators and Variables.