Learn/Elixir/7. Collections
Lesson 7 of 8
Sign in

Elixir, lesson 7

Collections

Real programs deal with many values at once: a list of scores, a table of prices. Elixir's main collections are lists, tuples and maps.

Lists

A list holds any number of values in order, inside square brackets:

Lists are linked lists: each item points to the next one. Adding to the front with [item | list] is instant, while reaching the last item means walking the whole list. Like every Elixir value, a list never changes; [60 | scores] builds a new list and leaves scores alone.

The Enum module does the heavy lifting:

map transforms every item, filter keeps the items that pass a test, and reduce (from the loops lesson) folds them into one value. These three cover most of what loops do elsewhere.

2 exercises to try what you just read.

Exercise 1

Score stats

Press Ctrl Enter or Check to test your code.

Exercise 2

Vote tally

Press Ctrl Enter or Check to test your code.

Tuples

A tuple groups a fixed number of values: {"apple", 3}. Use tuples for small bundles that belong together, such as a name with a count, or a result like {:ok, value}. You take them apart with pattern matching: {fruit, count} = {"apple", 3}.

Maps

A map stores values under keys, like a dictionary:

Map.update/4 changes one key based on its old value, with a starting value for new keys. That is exactly what you need for counting:

Counting is so common that Enum.frequencies/1 does it in one call. When you walk over a map with Enum, each entry arrives as a {key, value} tuple. Maps do not promise any order, so sort the entries when the order matters: Enum.sort(counts) sorts tuples by key first.

From a line of text to a list

String.split/1 breaks a string on any whitespace and drops empty pieces, so "4 8 15\n" becomes ["4", "8", "15"]. Pipe that into Enum.map(&String.to_integer/1) to get numbers. The &String.to_integer/1 syntax passes the named function itself as an argument.

Further reading

  • Getting started: Lists and tuples
  • Getting started: Keyword lists and maps
  • The Enum module and the Map module

Read a line of game scores separated by spaces and print four statistics.

Input: one line with at least one whole number. Output:

That is for the input 12 6 21 3.

A class votes for the name of its pet fish. Count the votes for each name.

Input: the first line is the number of votes N (0 or more). Then N lines follow, each with one name (a single word).

Output: one line per name, name: votes, sorted alphabetically by name. If there are no votes, print No votes.

prints

scores = [72, 95, 88]
IO.inspect(scores)         # [72, 95, 88]
IO.puts(length(scores))    # 3
more = [60 | scores]       # [60, 72, 95, 88]
Enum.sum(scores)                          # 255
Enum.max(scores)                          # 95
Enum.sort(scores)                         # [72, 88, 95]
Enum.map(scores, fn s -> s + 5 end)       # [77, 100, 93]
Enum.filter(scores, fn s -> s >= 80 end)  # [95, 88]
stock = %{"apple" => 3, "pear" => 0}
IO.puts(stock["apple"])           # 3
stock = Map.put(stock, "plum", 7) # add or replace a key
IO.puts(Map.get(stock, "kiwi", 0)) # 0, the default for a missing key
counts =
  Enum.reduce(["tea", "coffee", "tea"], %{}, fn drink, acc ->
    Map.update(acc, drink, 1, fn old -> old + 1 end)
  end)
# %{"coffee" => 1, "tea" => 2}
Count: 4
Min: 3
Max: 21
Sum: 42
4
Bubbles
Finn
Bubbles
Nemo
Bubbles: 2
Finn: 1
Nemo: 1