Elixir는 Erlang 가상 머신(BEAM) 상에서 확장성 있고 결함에 강한 시스템을 구축하기 위해 설계된 동적 함수형 프로그래밍 언어입니다.
🔗 관련 문서: Elixir 메타프로그래밍 치트시트 · Absinthe GraphQL 치트시트 · Phoenix 프레임워크 치트시트
시작하기 (Getting Started)
# hello.exs
defmodule Greeter do
def greet(name) do
message = "Hello, " <> name <> "!"
IO.puts(message)
end
end
Greeter.greet("world")
Elixir CLI로 실행:
elixir hello.exs
# => Hello, world!
변수 및 불변성 (Variables & Immutability)
age = 23
age = 24 # 재바인딩 (기존 메모리 값을 직접 수정하지 않음)
맵 (Maps)
user = %{
name: "John",
city: "Melbourne"
}
IO.puts("Hello, " <> user.name)
리스트 (Lists)
users = ["Tom", "Dick", "Harry"]
Enum.each(users, fn user ->
IO.puts("Hello " <> user)
end)
파이프 연산자 (Pipe Operator |>)
좌측 표현식의 실행 결과를 우측 함수 호출의 첫 번째 인자로 전달합니다:
source
|> transform(:hello)
|> print()
# 다음과 동일한 동작:
print(transform(source, :hello))
패턴 매칭 (Pattern Matching)
Elixir에서 = 기호는 단순 할당이 아닌 구조적 패턴 매칭 연산자입니다:
user = %{name: "Tom", age: 23}
%{name: username} = user
# username is bound to "Tom"
# 핀 연산자(^)는 변수를 재바인딩하지 않고 기존 값과 비교
x = 1
^x = 1 # 일치 성공
# ^x = 2 # 불일치 예외 발생 MatchError
함수 헤더에서의 패턴 매칭
defmodule UserGreeter do
def greet(%{name: username}) do
IO.puts("Hello, " <> username)
end
end
제어 흐름 (Control Flow)
if & unless
if status == :ok do
"Ready"
else
"Pending"
end
case
case {1, 2, 3} do
{4, 5, 6} -> "No match"
{1, x, 3} -> "Matches and binds x to 2"
_ -> "Wildcard matches any value"
end
cond
조건을 순차적으로 평가하여 최초로 참이 되는 블록을 실행합니다:
cond do
1 + 1 == 3 -> "Never matches"
2 * 5 == 12 -> "Neither"
true -> "Matches (acts as else)"
end
with
여러 패턴 매칭 단계를 안전하게 연결하며 첫 에러 발생 시 즉시 중단합니다:
with {:ok, {int, _}} <- Integer.parse("123abc"),
{:ok, datetime, _offset} <- DateTime.from_iso8601("2026-10-25T12:00:00Z") do
DateTime.add(datetime, int, :second)
else
:error -> "Invalid integer format"
{:error, :invalid_format} -> "Invalid ISO datetime"
_ -> "Unhandled error"
end
타입 및 연산자 (Types & Operators)
is_atom/1 is_boolean/1 is_binary/1
is_integer/1 is_float/1 is_number/1
is_list/1 is_map/1 is_tuple/1
is_nil/1 is_function/1 is_pid/1
컬렉션 및 자료구조 (Collections & Data Structures)
Maps
m = %{name: "Alice", age: 30}
# 기존 키 업데이트 문법
m = %{m | age: 31}
# Map 모듈 주요 함수
Map.get(m, :name) # "Alice"
Map.put(m, :city, "Tokyo") # Adds :city
Map.delete(m, :age) # Removes :age
Map.merge(m, %{active: true}) # Merges maps
Lists & Enums
list = [1, 2, 3, 4]
# 앞부분 추가 O(1) 및 뒷부분 결합 O(N)
[0 | list] # [0, 1, 2, 3, 4]
list ++ [5] # [1, 2, 3, 4, 5]
# Enum 주요 연산
Enum.map(list, &(&1 * 2)) # [2, 4, 6, 8]
Enum.filter(list, fn x -> rem(x, 2) == 0 end) # [2, 4]
Enum.reduce(list, 0, &+/2) # 10
함수 정의 (Functions)
# 익명 함수
add = fn a, b -> a + b end
add.(2, 3) # 5
# 캡처 문법
square = &(&1 * &1)
square.(5) # 25
# 기존 함수 참조 캡처
fun = &String.upcase/1
fun.("hello") # "HELLO"
구조체 및 프로토콜 (Structs & Protocols)
defmodule User do
defstruct name: "", age: nil
end
user = %User{name: "Alice", age: 30}
user.name # "Alice"
defprotocol Blank do
@doc "Returns true if data is empty"
def blank?(data)
end
defimpl Blank, for: List do
def blank?([]), do: true
def blank?(_), do: false
end
Blank.blank?([]) # true
내포 표현식 (for)
for n <- 1..5, do: n * 2
# => [2, 4, 6, 8, 10]
for n <- 1..10, rem(n, 2) == 0, do: n
# => [2, 4, 6, 8, 10]
for {k, v} <- %{a: 1, b: 2}, into: %{}, do: {k, v * 10}
# => %{a: 10, b: 20}
동작 사양 및 타입 스펙 (Behaviours & Type Specs)
defmodule Parser do
@callback parse(String.t()) :: {:ok, any()} | {:error, String.t()}
@callback extensions() :: [String.t()]
end
defmodule JSONParser do
@behaviour Parser
@impl Parser
def parse(str), do: {:ok, str}
@impl Parser
def extensions, do: [".json"]
end