0Pricing
Elixir & Phoenix: Scalable Backend Development · 课时

函数、模块与管道操作

学习定义函数、将代码组织成模块,并使用管道运算符清晰地转换数据。

函数、模块与管道操作 是 CoddyKit 上的免费 Elixir & Phoenix: Scalable Backend Development 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Elixir & Phoenix: Scalable Backend Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Introduction to Elixir Functions

In Elixir, functions are the building blocks of your programs. They take inputs, perform operations, and return outputs.

Elixir functions are designed to be pure: they don't change data outside their scope and always produce the same output for the same input. This makes your code predictable and easier to reason about.

Defining Public Functions

You define public functions using the def keyword. These functions can be called from anywhere within your application, provided they are part of a module.

Let's create a simple function that adds two numbers:

defmodule MathOperations do
  def add(a, b) do
    a + b
  end
end

IO.puts "Sum of 5 and 3: #{MathOperations.add(5, 3)}"

Defining Private Functions

Sometimes you need helper functions that should only be used internally within a module. For these, you use the defp keyword.

Private functions cannot be called directly from outside their defining module. This helps encapsulate logic.

defmodule SecretOperations do
  defp secret_add(a, b) do
    a + b + 10 # A 'secret' addition
  end

  def public_operation(x, y) do
    secret_add(x, y)
  end
end

IO.puts "Result of public operation: #{SecretOperations.public_operation(2, 3)}"
# SecretOperations.secret_add(1, 2) would cause an error if called directly outside the module.

Function Arity and Clauses

Arity refers to the number of arguments a function takes. Elixir allows you to define multiple function clauses with the same name but different arities or different patterns for arguments.

This enables powerful pattern matching (covered in a previous lesson) to handle different scenarios cleanly within a single function definition.

defmodule Greeter do
  def greet("Alice"), do: "Hello, Alice!"
  def greet(name), do: "Hi there, #{name}!"
end

IO.puts Greeter.greet("Alice")
IO.puts Greeter.greet("Bob")

Anonymous Functions

Anonymous functions (also called lambdas) are functions without a name. They are often used when you need to pass a function as an argument to another function, or for short, one-off operations.

You define them using the fn keyword.

adder = fn a, b -> a + b end
multiplier = fn x, y -> x * y end

IO.puts "Anonymous add: #{adder.(10, 20)}"
IO.puts "Anonymous multiply: #{multiplier.(4, 5)}"

Organizing Code with Modules

Modules in Elixir are containers for organizing related functions and data. They help prevent naming conflicts and make your code more structured and maintainable.

You define a module using the defmodule keyword. It's common practice for module names to start with an uppercase letter, following Elixir's naming conventions.

Creating Your First Module

Let's put our add function inside a module called Calculator. This makes it clear that the add function is part of a set of calculator-related operations.

defmodule Calculator do
  def add(a, b) do
    a + b
  end

  def subtract(a, b) do
    a - b
  end
end

IO.puts "Module defined!"

Calling Module Functions

To call a function defined within a module, you use the module's name, followed by a dot (.), and then the function name with its arguments.

This explicit naming helps you understand where a function comes from.

defmodule Calculator do
  def add(a, b), do: a + b
  def subtract(a, b), do: a - b
end

IO.puts "10 + 5 = #{Calculator.add(10, 5)}"
IO.puts "10 - 5 = #{Calculator.subtract(10, 5)}"

Introducing the Pipe Operator `|>`

The pipe operator |> is one of Elixir's most beloved features. It makes sequences of function calls incredibly readable, flowing data from one function to the next.

Think of it as taking the result of the expression on the left and passing it as the first argument to the function call on the right.

Pipelining in Action

Instead of nesting function calls like function_c(function_b(function_a(data))), the pipe operator lets you write it as data |> function_a() |> function_b() |> function_c().

This reads like a series of steps, making complex data transformations much clearer.

defmodule DataProcessor do
  def double(x), do: x * 2
  def add_five(x), do: x + 5
  def to_string(x), do: to_string(x)
end

result = 10 
         |> DataProcessor.double() 
         |> DataProcessor.add_five() 
         |> DataProcessor.to_string()

IO.puts "Processed result: #{result}"

Check Your Understanding

Which of the following statements about Elixir functions, modules, and the pipe operator are true?

Recap: Functions, Modules & Pipes

Great job! In this lesson, you learned the essentials of organizing and transforming data in Elixir:

  • How to define public (`def`) and private (`defp`) functions.
  • The importance of modules (`defmodule`) for structuring your code.
  • How the pipe operator (`|>`) dramatically improves readability for sequential data transformations.

These concepts are fundamental to writing clear, maintainable, and functional Elixir applications. Keep practicing!

常见问题解答

「函数、模块与管道操作」课时是免费的吗?

是的 — 「函数、模块与管道操作」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Elixir & Phoenix: Scalable Backend Development 课程的其余内容,请升级到 CoddyKit PRO。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。

「函数、模块与管道操作」这节课中我会学到什么?

学习定义函数、将代码组织成模块,并使用管道运算符清晰地转换数据。 你通过在浏览器中直接运行的动手代码来练习 Elixir & Phoenix: Scalable Backend Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Elixir & Phoenix: Scalable Backend Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Elixir & Phoenix: Scalable Backend Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「函数、模块与管道操作」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Elixir & Phoenix: Scalable Backend Development 课中编写并运行代码吗?

能。每节 Elixir & Phoenix: Scalable Backend Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 函数、模块与管道操作
  2. 处理可枚举集合
  3. 递归与高阶函数
  4. 使用 Stream 模块进行惰性求值
← 返回 Elixir & Phoenix: Scalable Backend Development