Elixir에서는 하나의 함수가 여러 개의 절을 가질 수 있어요. 이는 함수의 인자를 패턴 매칭하고 가드를 사용함으로써 가능해요.
# pattern matching the argument
def number(7) do
"Awesome, that's my favorite"
end
# using a guard
def number(n) when is_integer(n) do
"That's not my favorite"
end
def number(_n) do
"That's not even a number!"
end
FunctionClauseError가 발생해요._를 붙여야 해요. 그렇지 않으면 컴파일러에서 경고가 발생해요.fn
13 -> "Awesome, that's my favorite"
_ -> "That's not my favorite"
end
여러 절 함수는 다른 프로그래밍 언어에서 알 수 있는 함수 오버로딩과 혼동하면 안 돼요. Elixir에서 함수는 이름과 인자의 개수로만 식별되며, 인자의 타입은 식별에 사용되지 않아요(정적 타입이 없기 때문이에요). 예제의 number/1 함수는 몇 개의 절을 가지고 있든 하나의 함수로 간주돼요.