More Complex List Patterns

Not every list problem can be easily solved by processing one element at a time. Fortunately, the join operator, |, supports multiple values to its left. Thus, you could write

 iex>​ [ 1, 2, 3 | [ 4, 5, 6 ]]
 [1, 2, 3, 4, 5, 6]

The same thing works in patterns, so you can match multiple individual elements as the head. For example, this program swaps pairs of values in a list:

 defmodule​ Swapper ​do
 def​ swap([]), ​do​: []
 def​ swap([ a, b | tail ]), ​do​: [ b, a | swap(tail) ]
 def​ swap([_]), ​do​: ​raise​ ​"​​Can't swap a list with an odd number of elements"
 end

We can play with it in IEx:

 iex>​ c ​"​​swap.exs"
 [Swapper]
 iex>​ Swapper.swap [1,2,3,4,5,6]
 [2, 1, 4, 3, 6, 5]
 

Get Programming Elixir ≥ 1.6 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.