0Pricing
Elixir & Phoenix: Scalable Backend Development · 강의

재귀와 고차 함수

함수형 프로그래밍의 기본 개념인 재귀를 이해하고 동작을 추상화하는 고차 함수를 살펴봅니다.

재귀와 고차 함수은(는) CoddyKit의 무료 Elixir & Phoenix: Scalable Backend Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Elixir & Phoenix: Scalable Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Meet Recursion in Elixir

Welcome to recursion! In functional programming, recursion is a powerful technique where a function calls itself to solve a problem.

Instead of using loops (like for or while in other languages), Elixir often relies on recursion to iterate over data or repeat actions. It's a core concept you'll use a lot!

The Two Pillars of Recursion

Every recursive function needs two main parts to work correctly:

  • Base Case: This is the stopping condition. It defines when the function should stop calling itself and return a direct result. Without it, your function would run forever!
  • Recursive Step: This is where the function calls itself again, but with a smaller or simpler version of the original problem. Each call moves closer to the base case.

Recursion in Action: Factorial

Let's see recursion with a classic example: calculating the factorial of a number. The factorial of n (written as n!) is the product of all positive integers less than or equal to n. For example, 5! = 5 * 4 * 3 * 2 * 1 = 120.

Notice how factorial(n) calls factorial(n - 1) until it hits the base case of 0.

defmodule Math do
  def factorial(0), do: 1
  def factorial(n) when n > 0, do: n * factorial(n - 1)
end

IO.puts "Factorial of 5: #{Math.factorial(5)}"

Efficient Recursion: Tail Calls

While recursion is great, naive recursion can sometimes lead to performance issues or 'stack overflows' for very deep calls.

Elixir (and the Erlang VM) offers Tail Call Optimization (TCO). If the recursive call is the very last operation in a function, the VM can optimize it, preventing new stack frames from being created. This makes tail-recursive functions as efficient as loops!

Optimizing with Tail Recursion

To achieve TCO, we often use an accumulator. This is an extra argument passed to the function that collects the result as the recursion progresses.

Compare this version to the previous one. The recursive call factorial(n - 1, n * acc) is the last thing happening in the function, making it tail-recursive.

defmodule Math do
  # Public interface, calls the private tail-recursive function
  def factorial(n), do: factorial(n, 1)

  # Private tail-recursive function with accumulator
  defp factorial(0, acc), do: acc
  defp factorial(n, acc) when n > 0, do: factorial(n - 1, n * acc)
end

IO.puts "Tail factorial of 5: #{Math.factorial(5)}"

Functions as First-Class Citizens

Now, let's explore Higher-Order Functions (HOFs). In Elixir, functions are 'first-class citizens'. This means you can:

  • Pass functions as arguments to other functions.
  • Return functions as results from other functions.
  • Assign functions to variables.

HOFs enable powerful abstractions, making your code more concise, flexible, and reusable.

Transforming Lists with Enum.map

Enum.map/2 is one of the most common HOFs. It takes an enumerable (like a list) and a function. It applies that function to each element and returns a new list with the transformed elements.

It never modifies the original list, embracing Elixir's immutability.

numbers = [1, 2, 3, 4]
doubled_numbers = Enum.map(numbers, fn n -> n * 2 end)

IO.puts "Original: #{inspect numbers}"
IO.puts "Doubled: #{inspect doubled_numbers}"

Filtering Lists with Enum.filter

Another handy HOF is Enum.filter/2. It takes an enumerable and a function that should return a boolean (true or false).

It returns a new list containing only the elements for which the function returned true. It's perfect for selecting specific items from a collection.

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = Enum.filter(numbers, fn n -> rem(n, 2) == 0 end)

IO.puts "Original: #{inspect numbers}"
IO.puts "Even: #{inspect even_numbers}"

Aggregating with Enum.reduce

Enum.reduce/3 is perhaps the most powerful HOF for working with enumerables. It takes an enumerable, an initial accumulator value, and a function.

It iterates through the collection, applying the function to each element and the current accumulator, eventually reducing the entire collection to a single value.

numbers = [1, 2, 3, 4]
sum = Enum.reduce(numbers, 0, fn n, acc -> n + acc end)
product = Enum.reduce(numbers, 1, fn n, acc -> n * acc end)

IO.puts "Numbers: #{inspect numbers}"
IO.puts "Sum: #{sum}"
IO.puts "Product: #{product}"

Anonymous Functions and HOFs

You've seen fn n -> n * 2 end. These are anonymous functions (or lambdas). Elixir provides a shorthand for simple anonymous functions:

  • &1 refers to the first argument.
  • &2 refers to the second argument, and so on.
  • &(&1 + &2) is equivalent to fn a, b -> a + b end.

This makes HOF calls even more concise!

numbers = [1, 2, 3, 4]
doubled_short = Enum.map(numbers, &(&1 * 2))
even_short = Enum.filter(numbers, &(rem(&1, 2) == 0))

IO.puts "Doubled (short): #{inspect doubled_short}"
IO.puts "Even (short): #{inspect even_short}"

Test Your HOF Knowledge

Higher-Order Functions are a cornerstone of functional programming in Elixir. Let's check your understanding.

Recursion & HOFs: Key Takeaways

Great job! In this lesson, you've grasped two fundamental concepts in functional Elixir:

  • Recursion: A function calling itself, defined by a base case and a recursive step.
  • Tail Call Optimization (TCO): An important Elixir feature for efficient, stack-safe recursion, often achieved with an accumulator.
  • Higher-Order Functions (HOFs): Functions that take other functions as arguments or return them, like Enum.map, Enum.filter, and Enum.reduce.
  • Anonymous Functions: Concise ways to define functions inline, often used with HOFs, including the &1 shorthand.

These tools are essential for writing expressive and powerful Elixir code. Keep practicing!

자주 묻는 질문

“재귀와 고차 함수” 강의는 무료인가요?

네 — “재귀와 고차 함수” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Elixir & Phoenix: Scalable Backend Development 강의 전체를 잠금 해제할 수 있습니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.

“재귀와 고차 함수”에서 뭘 배우나요?

함수형 프로그래밍의 기본 개념인 재귀를 이해하고 동작을 추상화하는 고차 함수를 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 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 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 함수, 모듈 및 파이프 연결
  2. 열거 가능한 컬렉션 다루기
  3. 재귀와 고차 함수
  4. Stream 모듈을 사용한 지연 평가
← Elixir & Phoenix: Scalable Backend Development(으)로 돌아가기