More Complex List Patterns
Understand lists by implementing different kinds of operations in different cases.
We'll cover the following...
We'll cover the following...
The join operator |
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, we can write the following:
iex> [ 1, 2, 3 | [ 4, 5, 6 ]]
[1, 2, 3, 4, 5, 6]
The same thing works in patterns, so we can match multiple individual elements as the head. For example, the following program swaps pairs of values in a list.
Run the Swapper.swap([1,2]) command in the terminal below.
defmodule First.MixProject do
use Mix.Project
def project do
[
app: :first,
version: "0.1.0",
elixir: "~> 1.12",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
def hello do
[
IO.puts("Hello")
]
end
end
List example in Elixir
The third definition of swap (at line 6) matches a list with a single element. This definition will execute if we get to the end of the recursion and have only one ...