Elixir basics · Lesson 03 (open contents)
Put values together
Use lists, tuples, and maps to hold groups of data.
Three collections for three jobs
All three hold several values, but you read them in different ways.
# A list keeps its order
hd(["peach", "plum", "apricot"])
# A tuple keeps a status and data together
elem({:ok, 42}, 1)
# A map finds a value by name
%{name: "Robin", score: 92}.scorehd(["peach", "plum", "apricot"])returns the first value,"peach".elem({:ok, 42}, 1)returns42. Positions start at 0..scorereads92from the map.
Read from the first line down
hd(["peach", "plum", "apricot"])reads the first item of a non-empty list. Do not use it with an empty list yet.- The
1inelem({:ok, 42}, 1)is a position. A tuple's first position is numbered0. - When a map key is an atom, you can read it with dot notation such as
.score.
Symbols are not secret signs
[ ]Square brackets wrap a list.
{ }Braces wrap a tuple.
%{key: value}A percent sign and braces make a map. The key is on the left of the colon.
Match each name to its meaning
list
An ordered collection in square brackets, such as ["peach", "plum"]. It is useful when values are handled in order.
tuple
A fixed group in braces, such as {:ok, 200}. It often holds several parts of one result.
map
A collection that finds a value by key, such as %{name: "Robin"}.
Why these forms are useful
When one value is not enough, a collection can hold several. A shopping list has an order, so a list fits. A result and its status often travel together in a tuple.
A map finds values by name. In a student record, :name points to the name and :score points to the score. A reader does not need to guess what each position means.
First learn to read collections and take values out. You can learn how to update them later.
Close the answer and try
Make a map for a book. Store its title and number of pages, then read the page count.
# Add two keys, then read the page count with a dot
%{____: "Journey to the West", ____: 100}.____Target result: The result should be 100.
Stuck? Read one hint
You can use the keys title and pages.
After you run it, see one answer
# A map stores facts under named keys
# An atom key can be read with a dot
%{title: "Journey to the West", pages: 100}.pagesThink about it: Should a name and score go in `["Robin", 92]` or `%{name: "Robin", score: 92}`?
Prefer the map while you are learning. name and score make the meaning of each value clear.
Remember these three lines
- 1
A list suits values that will be handled in order.
- 2
A tuple often ties a status to a result.
- 3
A map uses keys to explain its values.