← Back to lesson 04: Put values together

Put values together: full examples and further reading

The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.

Use lists, tuples, and maps to hold groups of data.

Run one list, tuple, and map expression, then read one value from each collection.

Three collections for three jobs

All three hold several values, but you read them in different ways.

Original full example
# 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}.score

hd(["peach", "plum", "apricot"]) returns the first value, "peach".

elem({:ok, 42}, 1) returns 42. Positions start at 0.

.score reads 92 from the map.

Steps for the full example

  1. hd(["peach", "plum", "apricot"]) reads the first item of a non-empty list. Do not use it with an empty list yet.
  2. The 1 in elem({:ok, 42}, 1) is a position. A tuple's first position is numbered 0.
  3. When a map key is an atom, you can read it with dot notation such as .score.

Original lesson notes

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.

Symbols and terms
[ ]
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.
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"}.

Original full exercise

Make a map for a book. Store its title and number of pages, then read the page count.

Exercise starter
# Add two keys, then read the page count with a dot
%{____: "Journey to the West", ____: 100}.____

The result should be 100.

Show hint

You can use the keys title and pages.

Show original answer
Reference answer
# A map stores facts under named keys
# An atom key can be read with a dot
%{title: "Journey to the West", pages: 100}.pages
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.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references