Pattern matching on tuples

The following snippet shows how pattern matching can be done on tuples:

iex> {number, representation} = {3.1415, "π"}{3.1415, "π"}iex> number3.1415iex> representation"π"

The process here is the same as we have described in the preceding snippet. By setting the {number, description} pattern on the left-hand side, we're stating that we expect a tuple with two values—again, if that's not the case, a MatchError will be raised. In this case, the match succeeds, and we can see that the variables number and representation are bound to the expected values.

Unlike Erlang, Elixir allows you to rebind a variable, which is why the following works: iex> a = 1 1 iex> a = 7 7 However, a variable can only bind once per match: ...

Get Mastering 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.