Want to learn?
Elixir Course Online | Prograils - Software Development Company
Keywords lists
Representation
You are already familiar with both lists and tuples. The keyword list is a list of two-element tuples where the first element is an atom and the second element can be any value:
[{:exit_on_close, true}, {:active, :once}, {:packet_size, 1024}]
Since it's pretty common to use keyword lists when passing options to a function, there is an alternative syntax:
[exit_on_close: true, active: :once, packet_size: 1024]
This syntax is entirely equivalent to the previous one. You can use both of these. It's also worth to note that keys (atoms) don't have to be unique:
iex> [color: "red", color: "blue"]
[color: "red", color: "blue"]
Accessing keyword list elements
You can use []
to access first occurrence of element with given atom key:
iex> list = [a: 1, b: 2, a: 3]
[a: 1, b: 2, a: 3]
iex> list[:a]
1
Adding new elements with pipe operator
You can add new element to keyword list with pipe operator:
iex> list = [a: 1, b: 2, c: 3]
[a: 1, b: 2, c: 3]
iex> list = [{:d, 4} | list]
[d: 4, a: 1, b: 2, c: 3]
Modifying keyword list elements
Just like with regular lists, you can add a new element to keyword list with ++
operator and delete with --
operator:
iex> list = [a: 1, b: 2]
[a: 1, b: 2]
iex> list = list ++ [c: 3]
[a: 1, b: 2, c: 3]
iex> list = list -- [c: 3]
[a: 1, b: 2]