Chuyển đến nội dung
Skillpedia
Lập trình chung48k · #5891

elixir

Skill này làm gì

Hướng dẫn này dạy cách viết code Elixir hiệu quả và rõ ràng hơn. Nó chỉ cách tổ chức code tốt hơn, xử lý lỗi và dùng các tính năng của ngôn ngữ.

Khi nào nên dùng

  • ✓Khi học Elixir và muốn viết code chất lượng cao.
  • ✓Khi xem lại code Elixir để làm nó dễ đọc hơn.
  • ✓Khi gặp khó khăn viết Elixir theo đúng phong cách của ngôn ngữ.

Liên kết skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/elixir/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/elixir/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để viết hàm kiểm tra một số chẵn hiệu quả hơn trong Elixir?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Hướng dẫn so sánh các cách làm thông thường với ví dụ code, cho thấy cách dùng “pattern matching” và toán tử “pipe” để đơn giản hóa logic và tránh lỗi.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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

  1. Pattern Matching & Guards
  2. Pipe Operator & Transforms
  3. Processes & OTP
  4. Error Handling
  5. Collections & Enum
  6. Structs & Protocols
  7. 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)

…
Câu hỏi thường gặp

“Pattern matching” là gì?

Đây là cách kiểm tra và trích xuất dữ liệu từ cấu trúc code một cách gọn gàng, ví dụ kiểm tra một map có khóa cụ thể và lấy giá trị của khóa đó cùng lúc.

Toán tử “pipe” (`|>`) là gì?

Toán tử này cho phép nối các lần gọi hàm một cách dễ đọc, truyền kết quả của hàm này làm đối số cho hàm tiếp theo, từ trên xuống dưới.

“Let it crash” nghĩa là gì?

Đó là triết lý trong Elixir: thay vì cố bắt mọi lỗi có thể xảy ra, bạn để chương trình lỗi theo cách kiểm soát được, và một hệ thống giám sát sẽ khởi động lại phần cần thiết.

Chi tiết

Mô tả gốc của tác giả

Language-specific super-code guidelines for elixir.

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#5891
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự