Atoms
Mix.install([
{:kino, github: "livebook-dev/kino", override: true},
{:kino_lab, "~> 0.1.0-dev", github: "jonatanklosko/kino_lab"},
{:vega_lite, "~> 0.1.4"},
{:kino_vega_lite, "~> 0.1.1"},
{:benchee, "~> 0.1"},
{:ecto, "~> 3.7"},
{:math, "~> 0.7.0"},
{:faker, "~> 0.17.0"},
{:utils, path: "#{__DIR__}/../utils"}
])
Navigation
Atoms
Atoms are named constants. In other words, their name is their value.
Atoms are often used to represent common constants in your program. For example, they often represent the :success or :error of a program.
:success
:error
They might also be used to represent the state of some action. For example:
:completed
:in_progress
:starting
You might wonder why we have both strings and atoms because they seem to do the same thing. One primary reason is performance. Atoms are stored in an atom table and can be referenced by an integer. This makes it way faster to check if two atoms are equal.
What is an atom table? Imagine it like an excel spreadsheet.
Each value has a numbered key, so checking 1 = 1
is a lot easier than checking.
"HeLloWorld = HeLloWorLd"
.
Atoms are defined using a colon :
and a series of letters, digits, and certain valid symbols.
Rules For Naming Atoms
There are specific rules for naming atoms, but fortunately you don’t need to memorize them! Instead, pay attention to the colors in your code. If you define an atom incorrectly, you’ll notice that it’s no longer blue.
Here are some valid atoms:
:hello
:my_atom1
Here are some invalid atoms, notice they are mostly white:
:$this_is_invalid
:!this_is_invalid
:2
:@
:$
:?
:invalid # spaces are not valid
Sometimes languages establish conventions. Conventions are common patterns of doing things which the community agrees upon. For example, In Elixir it’s conventional for atoms to have lowercase names separated by underscores.
While the following will work:
:MY_ATOM!
It’s unconventional to name an atom with capital letters.
You can use quotes with atoms to avoid name rules.
:"$Now we don't have to follow any rules. This is a valid atom (though unconventional)"
Secret Atoms nil
, false
, true
We use nil
when we want to represent a lack of something.
Under the hood, nil
is an atom :nil
.
We can use ===
to verify that :nil
and nil
are equivalent.
nil === :nil
The same goes for true
, and false
. They are
all atoms but omit the colon :
.
true === :true
false === :false
Your Turn
In the Elixir cell below, use ===
to check if nil
is equal to :nil
.
Check if true
is equal to :true
.
Check if false
is equal to :false
.
Optional Further Reading
Commit Your Progress
Run the following in your command line from the project folder to track and save your progress in a Git commit.
$ git add .
$ git commit -m "finish atoms section"