O'Reilly logo

Programming Elixir 1.2 by Dave Thomas

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

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.

 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, ...

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