Keyword lists

A keyword list is a list of two-item tuples whose first item is an atom: [colour: :red, size: 3] is the same value as [{:colour, :red}, {:size, 3}]. It is the shape an Elixir function takes its options in, like opts in String.split("a b", parts: 2), and it is the only named collection whose order and duplicate keys survive.

The literal and the tuple behind it

The short form writes the key and its value with a colon, and the long form writes the pair as a tuple. A function that reads the options asks for a key by its atom, and gets nil or a default when the key is absent:

literal.exs

opts = [colour: :red, size: 3] IO.inspect(opts) IO.inspect(Keyword.get(opts, :size)) IO.inspect(Keyword.fetch(opts, :colour)) IO.inspect(Keyword.fetch(opts, :missing)) IO.inspect(Keyword.get(opts, :missing, :default))

elixir literal.exs

[colour: :red, size: 3]
3
{:ok, :red}
:error
:default

Keyword.get/3 answers the value or the default, while Keyword.fetch/2 answers an :ok or :error tuple, the pair ok and error tuples explains. A keyword list looks like a map and is a list: it walks from the front on every lookup, which is why the lists a function takes stay short.

Repeated keys

A list keeps repeated keys, and the functions read them in order. Keyword.get/3 answers the first value, and Keyword.get_values/2 answers all of them, which is how a function takes an option twice and means both:

duplicates.exs

opts = [level: :info, level: :warn] IO.inspect(Keyword.get(opts, :level)) IO.inspect(Keyword.get_values(opts, :level)) IO.inspect(Keyword.put(opts, :level, :debug))

elixir duplicates.exs

:info
[:info, :warn]
[level: :debug]

Keyword.put/3 removes every pair with that key and puts the new one at the front, so the result has one value for it. A map cannot do this at all: the second write of a key replaces the first at once.

The options of a function

The options list is a default argument whose value is the empty list, and the body reads it with Keyword.get/3 for each option it knows. A caller writes the pairs without the brackets, and a variable that already holds a list goes in as it is:

options.exs

defmodule Greet do def hello(name, opts \\ []) do greeting = Keyword.get(opts, :greeting, "Hello") "#{greeting}, #{name}" end end opts = [greeting: "Hi"] IO.puts(Greet.hello("Ada")) IO.puts(Greet.hello("Ada", greeting: "Hi")) IO.puts(Greet.hello("Ada", opts))

elixir options.exs

Hello, Ada
Hi, Ada
Hi, Ada

The last argument of a call is the place the pairs can go without brackets, so a function with options always has them last. An option the function does not know is ignored rather than refused, and the documentation of the function names the ones it reads; Keyword.validate/2 answers an {:error, unknown_keys} tuple when the function refuses an unknown key.

put, put_new and delete

The module edits the list the way a list is edited: a new list comes back and the old one stays. Keyword.put_new/3 writes only when the key is absent, which is the difference between a default and an override:

update.exs

opts = [size: 3] IO.inspect(Keyword.put(opts, :size, 4)) IO.inspect(Keyword.put_new(opts, :size, 9)) IO.inspect(Keyword.delete(opts, :size)) IO.inspect(opts)

elixir update.exs

[size: 4]
[size: 3]
[]
[size: 3]

The last line prints the original unchanged, as every function of a collection in Elixir does. A program that calls Keyword.put/3 and drops its result has changed nothing, which is the same trap every immutable update has.

A keyword list or a map

The two stores answer different questions. A keyword list keeps order, takes duplicate keys and reads from the front, so it fits a short list of options where order matters. A map looks a key up in one step whatever the size, has unique keys and no order, so it fits data. A function that takes options uses the keyword list because a caller writes it as a call; a record the program keeps uses a map or a struct. The moment the options grow past a handful of keys, or the program looks one up in a loop, the map is the better shape.

The mistake: a keyword list read as a map

The dot form is the map form. On a keyword list the compiler accepts the line and the run stops with a BadMapError that prints the list it was given:

mistake.exs

opts = [size: 3] IO.inspect(opts.size)

elixir mistake.exs

** (BadMapError) expected a map, got:

    [size: 3]

    mistake.exs:3: (file)
    (elixir 1.19.7) lib/code.ex:1613: Code.require_file/2

The key is an atom and the store is a list, so the read is Keyword.get(opts, :size) or opts[:size]. The string key is the other half of the same mistake: Keyword.get(opts, "size") raises a FunctionClauseError, because the module only takes an atom key. A keyword list is read by atoms, in order, from a list.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a keyword list?

    Answer

    A list of two-item tuples whose first item is an atom

    The short form [key: value] is the pair {:key, value}, and a keyword list is a list of them.

  2. Which value does Keyword.get/3 answer when the list holds the key twice?

    Answer

    the first value

    The list is read from the front, so Keyword.get returns the first pair; get_values returns all.

  3. What does the dot form do on a keyword list?

    Answer

    Raises a BadMapError

    The dot is the map form; a list is not a map, and the run fails with a BadMapError.

  4. Why does a function take its options as the last argument?

    Answer

    Because the last argument can be written without brackets

    The pairs in the last position need no brackets, which is the call form the standard library uses.

  5. What does this program print? opts = [size: 3, size: 5] IO.inspect(Keyword.get_values(opts, :size))

    Answer

    [3, 5]

    get_values returns every value of the key in the order the list holds them.

  6. What does this program print? IO.inspect(Keyword.get([a: 1], :b, 0))

    Answer

    0

    The third argument of Keyword.get/3 is the default for a key the list does not hold.

  7. What does this program print? IO.inspect(Keyword.put([a: 1, a: 2], :a, 9))

    Answer

    [a: 9]

    Keyword.put removes every pair with the key and writes the new one once.

  8. What does this program print? IO.inspect(Keyword.put_new([size: 3], :size, 9))

    Answer

    [size: 3]

    put_new writes only when the key is absent, and this list already has it.

  9. What does this program do? defmodule Greet do def hello(name, opts \\ []) do greeting = Keyword.get(opts, :greeting, "Hello") "#{greeting}, #{name}" end end IO.puts(Greet.hello("Ada"))

    Answer

    Hello, Ada

    The default empty list means no option is set, so the default greeting is used.

  10. What does this program print? opts = [level: :info] IO.inspect(Keyword.fetch(opts, :level))

    Answer

    {:ok, :info}

    fetch answers the ok tuple when the key is there and :error when it is not.

Автор статьи: Arthur Isaev

Изображение баннера