May 2018
Intermediate to advanced
412 pages
9h 3m
English
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] |
| |
Read now
Unlock full access