O'Reilly logo

Introducing Elixir, 2nd Edition by J. David Eisenberg, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 or double 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required