Pattern matching on lists

Matching on lists is akin to matching on tuples. Here's a simple example:

iex> [first, second, third] = ["α", "β", "γ"]["α", "β", "γ"]iex> first"α"iex> second"β"iex> third"γ"

There's nothing new here. What if, for instance, we don't care about the second element of the list? That's where the  _ (underscore) anonymous variable is convenient:

iex> [first, _, third] = ["δ", "ε", "ζ"]["δ", "ε", "ζ"]iex> first"δ"iex> third"ζ"

We're again matching a list with three elements, but now bind the second element to the _ variable, which means that we accept anything in that position and we won't use its value.

 

 

The _ variable can never be read fromif you do so, you will get a CompileError: iex> _ ** (CompileError) iex:83: ...

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.