A collection is in programming a single unit that groups multiple values together. Elixir has different types of collections, one of the simplest being called List
. A list is indicated by square brackets []
.
["lemon", "peach", "cherry"]
A list can be associated to a variable, just like a piece of text:
fruits = ["lemon", "peach", "cherry"]
In the same way as for the text, calling the variable name will return you the full list:
fruits
You can easily add or subtract elements from lists using the ++
and --
operators:
["lemon", "peach", "cherry"] ++ ["ananas"]
["lemon", "peach", "cherry", "ananas"] -- ["ananas"]
What happens if you try to subtract an element that does not exist? Try that out!
As we saw in the previous chapter bonus exercise, the Elixir language itself offers you predefined functions that you can use to work with lists. Among the simplest functions are the ones to give you the first or last element in a list.
If we take our fruits
list from above, we can get the first element out of it with the following code:
List.first(fruits)
This might seem confusing, but if you look back at what you learned in Chapter 1, you should be able to see what is going on in that piece of code:
List
is amodule
, like the custom module we created earlierfirst
is afunction
. A predefined, built-in function inside theList
modulefruits
is the variable where you put your list, and you are passing it to the function when calling it
Just as we did earlier!
Give the list of fruits that we defined above can you get the following output out of it?
"Cherry"
Try it out here