패턴 일치와 제어 흐름
Elixir의 강력한 패턴 일치 기능과 `if`, `case`, `cond` 같은 핵심 제어 흐름 구문을 익힙니다.
패턴 일치와 제어 흐름은(는) CoddyKit의 무료 Elixir & Phoenix: Scalable Backend Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Elixir & Phoenix: Scalable Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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()Matching with Literals
Put a literal on the left and the match becomes an assertion: it succeeds only if both sides are equal, otherwise it raises. Handy for validation.
defmodule LiteralMatchDemo do
def run do
# This matches because 1 is equal to 1
1 = 1
IO.puts "1 = 1 matched successfully!"
# This matches because 'hello' is equal to 'hello'
"hello" = "hello"
IO.puts "'hello' = 'hello' matched successfully!"
# If you uncomment the line below, it will cause a MatchError
# 1 = 2
# IO.puts "This line would not be reached if 1 = 2 failed"
end
end
LiteralMatchDemo.run()Deconstructing Tuples
Matching shines on tuples — deconstruct them straight into variables, which is exactly how you unpack {:ok, value} results.
defmodule TupleMatchDemo do
def run do
# Match a tuple to extract its elements
{:person, name, age} = {:person, "Alice", 30}
IO.puts "Name: #{name}, Age: #{age}"
# Match a common result tuple
{:ok, data} = {:ok, "User fetched successfully"}
IO.puts "Status: ok, Data: #{data}"
# If you uncomment the line below, it will cause a MatchError
# {:error, reason} = {:ok, "Success"}
end
end
TupleMatchDemo.run()Deconstructing Lists
Deconstruct lists with the [head | tail] pattern: head is the first element, tail the rest. Use _ for parts you do not care about.
defmodule ListMatchDemo do
def run do
list = [1, 2, 3, 4, 5]
# Match head and tail
[head | tail] = list
IO.puts "Head: #{head}, Tail: #{inspect tail}"
# Match specific elements
[first, second, third | _rest] = list
IO.puts "First: #{first}, Second: #{second}, Third: #{third}"
# Match an empty list
[] = []
IO.puts "Empty list matched!"
end
end
ListMatchDemo.run()The Pin Operator (^)
The pin operator ^ says "do not rebind — match against this variable's current value" instead. Great for asserting equality.
defmodule PinOperatorDemo do
def run do
value_a = 10
value_b = 10
# This uses the current value of value_a (10) to match against value_b
# It succeeds because 10 matches 10
^value_a = value_b
IO.puts "Match successful: value_a = #{value_a}, value_b = #{value_b}"
value_c = 5
# If you uncomment the line below, it will cause a MatchError
# because ^value_a (10) is not equal to value_c (5)
# ^value_a = value_c
# IO.puts "This line would not be reached if ^value_a = value_c failed"
end
end
PinOperatorDemo.run()Simple Conditionals: if/unless
For simple branches use if and its mirror unless, each with an optional else. The cleanest tool for one true/false condition.
defmodule IfUnlessDemo do
def run do
number = 7
if number > 5 do
IO.puts "Number is greater than 5"
else
IO.puts "Number is 5 or less"
end
unless rem(number, 2) == 0 do
IO.puts "Number is odd"
else
IO.puts "Number is even"
end
end
end
IfUnlessDemo.run()Handling Multiple Patterns with case
The case expression matches one value against several patterns and runs the first that fits — pattern matching as control flow.
defmodule CaseExpressionDemo do
def run do
status = {:ok, "Data loaded"}
case status do
{:ok, message} ->
IO.puts "Success: #{message}"
{:error, reason} ->
IO.puts "Failed: #{reason}"
_ ->
IO.puts "Unknown status"
end
# Another example with a simple value
grade = "B"
case grade do
"A" -> IO.puts "Excellent!"
"B" -> IO.puts "Good job!"
_ -> IO.puts "Keep trying!"
end
end
end
CaseExpressionDemo.run()Multiple Conditions with cond
When you have many boolean checks (an if/else-if chain elsewhere), cond runs the first clause whose condition is true.
defmodule CondExpressionDemo do
def run do
score = 85
cond do
score >= 90 -> IO.puts "Grade: A"
score >= 80 -> IO.puts "Grade: B"
score >= 70 -> IO.puts "Grade: C"
true -> IO.puts "Grade: D or lower" # The 'true' clause acts as a catch-all
end
temperature = 25
cond do
temperature > 30 -> IO.puts "It's hot!"
temperature > 20 -> IO.puts "It's warm."
true -> IO.puts "It's cool."
end
end
end
CondExpressionDemo.run()Pattern Matching Challenge
Consider the following Elixir code snippet:
data = ["apple", {:fruit, "banana"}, "cherry"]
[first, {:fruit, second}, _] = dataWhat will be the final values of the variables first and second after this code executes?
Recap: Pattern Matching & Control
Recap: = matches, you deconstruct tuples and lists, ^ pins a value, and if/case/cond drive your control flow.
자주 묻는 질문
“패턴 일치와 제어 흐름” 강의는 무료인가요?
네 — “패턴 일치와 제어 흐름” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Elixir & Phoenix: Scalable Backend Development 강의 전체를 잠금 해제할 수 있습니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“패턴 일치와 제어 흐름”에서 뭘 배우나요?
Elixir의 강력한 패턴 일치 기능과 `if`, `case`, `cond` 같은 핵심 제어 흐름 구문을 익힙니다. 브라우저에서 직접 실행하는 실습 코드로 Elixir & Phoenix: Scalable Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Elixir & Phoenix: Scalable Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Elixir & Phoenix: Scalable Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“패턴 일치와 제어 흐름” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Elixir & Phoenix: Scalable Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Elixir & Phoenix: Scalable Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Elixir 언어 입문
- 기본 데이터 형식과 연산자
- 패턴 일치와 제어 흐름
- Elixir의 문자열, 바이너리 및 시길