elixir
它能做什么
本指南教你在 Elixir 编程语言中编写更高效、更清晰的代码。文中介绍了组织代码、处理错误和运用语言特性的更好方式。
适用场景
- ✓学习 Elixir 并希望写出高质量代码时。
- ✓审查 Elixir 代码、让其更易读时。
- ✓用 Elixir 写出惯用写法(idiomatic)的代码遇到困难时。
技能链接
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/elixir/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“如何在 Elixir 中更高效地编写一个判断数字是否为偶数的函数?”
每周 5 个新技能,1 分钟读完。
工作原理
本指南会用代码示例对比常见写法,展示如何使用“模式匹配”和管道操作符等特性来简化逻辑、避免错误。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Elixir / Erlang: Idiomatic Efficiency Reference
When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for elixir.
Table of Contents
- Pattern Matching & Guards
- Pipe Operator & Transforms
- Processes & OTP
- Error Handling
- Collections & Enum
- Structs & Protocols
- Anti-patterns specific to Elixir/Erlang
1. Pattern Matching & Guards {#patterns}
# ❌ Extracting with Map.get then checking
value = Map.get(map, :key)
if value != nil do
process(value)
end
# ✅ — pattern match directly
case map do
%{key: value} -> process(value)
_ -> :noop
end
# or with if:
if value = map[:key], do: process(value)
# ❌ Nested case for multiple conditions
case fetch_user(id) do
{:ok, user} ->
case validate(user) do
{:ok, valid_user} -> save(valid_user)
{:error, reason} -> {:error, reason}
end
{:error, reason} -> {:error, reason}
end
# ✅ — with clause
with {:ok, user} <- fetch_user(id),
{:ok, valid_user} <- validate(user) do
save(valid_user)
end
# ❌ if/else for known shapes
def area(shape) do
if shape.type == :circle do
:math.pi() * shape.radius * shape.radius
else
shape.width * shape.height
end
end
# ✅ — multi-clause function with pattern match
def area(%{type: :circle, radius: r}), do: :math.pi() * r * r
def area(%{type: :rect, width: w, height: h}), do: w * h
# ❌ Checking type at runtime
def process(x) do
if is_integer(x) and x > 0 do
x * 2
end
end
# ✅ — guard clause
def process(x) when is_integer(x) and x > 0, do: x * 2
def process(_), do: {:error, :invalid_input}
2. Pipe Operator & Transforms {#pipes}
# ❌ Nested function calls
String.trim(String.downcase(String.replace(input, ~r/\s+/, " ")))
# ✅
input
|> String.replace(~r/\s+/, " ")
|> String.downcase()
|> String.trim()
# ❌ Pipe into anonymous function awkwardly
data
|> (fn x -> x * 2 end).()
# ✅ — use then/1 or named function
data
|> then(&(&1 * 2))
# or better: extract a named function
data |> double()
# ❌ Single-step pipe (no gain in readability)
result = list |> Enum.count()
# ✅ — direct call for single operation
result = Enum.count(list)
Pipe when 2+ transforms. Direct call for single operation. First arg flows through pipe.
3. Processes & OTP {#otp}
# ❌ Raw spawn for stateful process
pid = spawn(fn -> loop(%{count: 0}) end)
send(pid, {:increment})
# ✅ — GenServer for stateful processes
defmodule Counter do
use GenServer
def start_link(init \\ 0), do: GenServer.start_link(__MODULE__, init)
def increment(pid), do: GenServer.call(pid, :increment)
@impl true
def init(count), do: {:ok, count}
@impl true
def handle_call(:increment, _from, count), do: {:reply, count + 1, count + 1}
end
# ❌ Spawning without linking (orphan process on crash)
spawn(fn -> do_work() end)
# ✅ — Task for fire-and-forget with supervision
Task.start(fn -> do_work() end)
# or for awaitable result:
task = Task.async(fn -> do_work() end)
result = Task.await(task)
# ❌ Manual process registry
Process.register(self(), :my_worker)
# ✅ — use Registry or named GenServer
{:ok, _} = Registry.start_link(keys: :unique, name: MyRegistry)
GenServer.start_link(Worker, arg, name: {:via, Registry, {MyRegistry, :my_worker}})
# ❌ try/catch in GenServer (breaks supervision)
def handle_call(:work, _from, state) do
try do
result = risky_operation()
{:reply, result, state}
catch
_ -> {:reply, :error, state}
end
end
# ✅ — let it crash; supervisor restarts
def handle_call(:work, _from, state) do
result = risky_operation()
{:reply, result, state}
end
"Let it crash" — supervisors handle recovery. Don't defensively catch inside GenServers.
4. Error Handling {#errors}
# ❌ Raising for expected failures
def find_user(id) do
case Repo.get(User, id) do
nil -> raise "User not found"
user -> user
end
end
# ✅ — tagged tuples for expected outcomes
def find_user(id) do
case Repo.get(User, id) do
nil -> {:error, :not_found}
user -> {:ok, user}
end
end
# ❌ Ignoring error tuple
{:ok, result} = might_fail() # crashes on {:error, _}
# ✅ — handle both cases
case might_fail() do
{:ok, result} -> process(result)
…
常见问题
什么是“模式匹配”(pattern matching)?
这是一种优雅地检查和提取代码结构中数据的方式。例如,可以在检查映射(map)是否包含某个键的同时,直接取出该键对应的值。
什么是管道操作符(`|>`)?
它可以把多个函数调用串联起来,让代码更易读。它会把前一个函数的结果作为参数传给下一个函数,从上到下依次执行。
“Let it crash”是什么意思?
这是 Elixir 的一种设计理念:不去试图捕获每一种可能的错误,而是让程序以可控的方式失败,再由监督机制重启必要的部分。
详情
热度
- GitHub 星标
- 48k
- 排名
- #5891
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …
同一仓库的更多技能
00-andruia-consultant
48k帮你的智能体启动或改进 AI 项目。它可以分析代码、推荐工具,并用西班牙语制定行动计划。
007
48k让你的智能体执行安全审计和威胁建模。它有助于保护项目免受攻击和漏洞的威胁。
10-andruia-skill-smith
48k帮你的智能体创建或改进 AI 工具。它可以定义工具的工作方式、编写文档,并验证其结构。
20-andruia-niche-intelligence
48k让你的智能体创建某个特定行业的摘要。它有助于借助可靠的信息来源,了解项目的背景、规则、使用模式和风险。