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, the following program swaps pairs of values in a list.

lists/swap.exs
 
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, ...

Get Programming Elixir now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.