Skip to content
Elixir

Filtrage par Motif

Le pattern matching est central en Elixir : omniprésent.

#pattern-matching#match

Code

elixir
# = is a match operator, not assignment
{:ok, value} = {:ok, 42}
IO.puts(value)  # 42

# Works with lists
[head | tail] = [1, 2, 3]
IO.puts(head)        # 1
IO.inspect(tail)     # [2, 3]

# Maps
%{name: name} = %{name: "Alice", age: 30}
IO.puts(name)  # "Alice"

# Function heads with multiple clauses
defmodule Math do
  def factorial(0), do: 1
  def factorial(n) when n > 0, do: n * factorial(n - 1)
end

# Case expression
case File.read("config.txt") do
  {:ok, contents} -> IO.puts("Loaded: #{contents}")
  {:error, :enoent} -> IO.puts("File not found")
  {:error, reason} -> IO.puts("Error: #{reason}")
end

# Pin operator (^) — match against existing value
x = 10
^x = 10   # matches
# ^x = 20  # MatchError!