Pattern Matching and Control Flow
Master Elixir's powerful pattern matching feature and essential control flow constructs like `if`, `case`, and `cond`.
Intro to Pattern Matching
Pattern matching is the heart of Elixir. Here = is a match operator, not assignment — it makes the left side equal the right.
Basic Variable Matching
The simplest match binds an unbound variable to a value. If it is already bound, Elixir instead checks that the two sides actually match.
defmodule BasicMatchDemo do
def run do
# 'a' is unbound, so it's assigned 10
a = 10
IO.puts "a is: #{a}"
# 'b' is unbound, so it's assigned 20
b = 20
IO.puts "b is: #{b}"
# This matches 'a' to the value of 'b' (20)
# 'a' is re-bound to 20
a = b
IO.puts "After a = b, a is: #{a}"
end
end
BasicMatchDemo.run()All lessons in this course
- Introduction to Elixir Language
- Basic Data Types and Operators
- Pattern Matching and Control Flow
- Strings, Binaries & Sigils in Elixir