Chapter 3. Atoms, Tuples, and Pattern Matching
Elixir programs are at heart a set of message requests and tools for processing them. Elixir provides tools that simplify the efficient handling of those messages, letting you create code that is readable (to programmers at least) while still running efficiently when you need speed.
Atoms
Atoms are a key component of Elixir. Technically they’re just another type of data, but it’s hard to overstate their impact on Elixir programming style.
Usually, atoms are bits of text that start with a colon, like :ok
or :earth
or :Today
. They can also contain underscores (_
) and at symbols (@
), like :this_is_a_short_sentence
or :me@home
. If you want more freedom to use spaces, you can start with the colon, and then put them in single quotes, like :'Today is a good day’
. Generally, the one-word lowercase form is easier to read.
Atoms have a value—it’s the same as their text:
iex(1)>
:test
:test
That’s not very exciting in itself. What makes atoms exciting is the way that they can combine with other types and Elixir’s pattern-matching techniques to build simple but powerful logical structures.
Pattern Matching with Atoms
Elixir used pattern matching to make the examples in Chapter 2 work, but it was very simple. The name of the function was the one key piece that varied, and as long as you provided a numeric argument, Elixir knew what you meant. Elixir’s pattern matching offers much more sophisticated possibilities, however, allowing you to match ...
Get Introducing Elixir now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.