Atoms
An atom is a constant whose name is its value. It starts with a colon, it is written once, and every copy of the same atom is the same object, so comparing two atoms costs nothing and matching one in a pattern is exact. Elixir uses them as labels: the tag of a result tuple, the key of an options list and the name of a status are atoms.
A constant with a name
The literal is a colon and the name. A name with letters, digits and underscores needs no quotes; a name with a space or a capital letter is written between double quotes after the colon. The check is_atom/1 is true for every one of them, and Atom.to_string/1 returns the name without the colon:
atoms.exs
status = :ok IO.puts(is_atom(status)) IO.puts(is_atom(true)) IO.puts(is_atom(nil)) IO.puts(Atom.to_string(status)) IO.inspect(:"two words")
elixir atoms.exs
true
true
true
ok
:"two words"
An atom is not a string and does not become one by itself. Its value is the atom itself, so it can be compared and matched but not joined or split. The conversion functions are Atom.to_string/1 for the name and String.to_existing_atom/1 for the way back, and the second one only accepts an atom the program already knows.
true, false and nil
The three words that look like keywords are plain atoms. true is the atom :true, false is :false and nil is :nil; the language gives them a short spelling because conditions use them all the time. is_boolean/1 accepts exactly the first two, and is_nil/1 exactly the third:
booleans.exs
IO.puts(is_boolean(true)) IO.puts(is_boolean(:ok)) IO.puts(is_nil(nil)) IO.puts(is_atom(nil))
elixir booleans.exs
true
false
true
true
The formatter writes true and nil in the short spelling, which is the same atom. Nothing else in the language is a boolean, which is why a function that returns :ok is not a predicate even though a condition accepts it.
Aliases are atoms
A module name written with a capital letter is an alias, and an alias is an atom with a long name. The alias IO stands for the atom :"Elixir.IO", which is why a module can be compared with an atom and why an error message sometimes prints the Elixir. prefix:
aliases.exs
IO.puts(is_atom(IO)) IO.puts(Atom.to_string(IO)) IO.puts(IO == :"Elixir.IO")
elixir aliases.exs
true
Elixir.IO
true
Every Elixir module lives under the Elixir. namespace at run time. Erlang modules, which were written before that convention, keep their plain names, which is why the Erlang functions of the next chapters are called as :erlang.system_info/1 and :timer.sleep/1 with a colon in front.
Atoms as tags
The most common use of an atom is a tag on a small tuple. A function that may fail returns {:ok, value} or {:error, reason}, and the caller matches the tag to decide which case it got. A map with atom keys uses them the same way:
results.exs
result = {:ok, 42} {:ok, value} = result IO.puts("the value is #{value}") IO.inspect(%{status: :ok, code: 200})
elixir results.exs
the value is 42
%{code: 200, status: :ok}
The match {:ok, value} = result takes the tuple apart and fails if the tag is not :ok. That is the shape every library follows, and the ok and error tuples lesson builds on it. The map keys are printed in alphabetical order, which is a property of the display, not of the map.
The mistake: an atom is not a string
An atom never turns into a binary by itself. Joining one to a string stops the program with an ArgumentError, and the message names the atom it got:
binary.exs
name = :ada IO.puts("Hello, " <> name)
elixir binary.exs
** (ArgumentError) construction of binary failed: segment 2 of type 'binary': expected a binary but got: :ada
binary.exs:2: (file)
(elixir 1.19.7) lib/code.ex:1613: Code.require_file/2
The fix is Atom.to_string(name) before the join, or a string from the start if the value is user input. The reverse direction is the one that needs care: String.to_atom/1 creates an atom that the VM keeps for its whole life, so a program that converts every word a user types leaks memory. Use String.to_existing_atom/1 when the name must be one the program already knows, and keep user input as a binary.
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.
-
What is an atom?
Answer
A constant whose name is its value
The atom is the value; :ok is not the text "ok" and needs a conversion to become one.
-
What are
true,falseandnil?Answer
Atoms with a short spelling
They are :true, :false and :nil, and is_atom/1 is true for all three.
-
What atom does the alias
IOstand for at run time?Answer
:"Elixir.IO"
An Elixir module lives under the Elixir. namespace, so the atom carries that prefix.
-
Why is
String.to_atom/1dangerous on user input?Answer
Every new atom stays in the VM for its whole life
The atom table is not garbage collected, so a program that creates atoms from arbitrary input grows it forever.
-
What does this program print?
IO.inspect(is_atom(IO))Answer
true
A module alias is an atom, so is_atom/1 returns true for IO.
-
What does this program print?
IO.inspect(Atom.to_string(:ok))Answer
"ok"
Atom.to_string/1 returns a binary with the name, and inspect shows its quotes.
-
What does this program print?
IO.inspect(:"two words")Answer
:"two words"
An atom with a space is quoted, and inspect prints it in that same notation.
-
What does this program print?
IO.puts(is_nil(nil))Answer
true
is_nil/1 is true only for the atom nil, and IO.puts/1 prints true.
-
What does this program do?
IO.puts("Hi " <> :ada)Answer
An ArgumentError, because an atom is not a binary
<>needs a binary on both sides, and :ada becomes text only through Atom.to_string/1. -
What does this program do?
IO.puts(String.to_existing_atom("brand_new_atom_name"))Answer
An ArgumentError, because no such atom exists yet
to_existing_atom/1 refuses to create one; only to_atom/1 does that.
Автор статьи: Arthur Isaev