elixir-pattern-matching
БесплатноБез исполняемых скриптовНе проверенUse when Elixir pattern matching including function clauses, case statements, with statements, and destructuring. Use for elegant control flow.
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
Elixir Pattern Matching
Master pattern matching in Elixir to write elegant, declarative code. This skill covers function patterns, case statements, guards, and destructuring across various data structures.
Basic Pattern Matching
# Simple assignment is pattern matching
x = 1
1 = x # This works because x matches 1
# Pattern matching with tuples
{:ok, value} = {:ok, "success"}
value # => "success"
# Will raise MatchError if patterns don't match
# {:error, _} = {:ok, "success"} # MatchError
# Pin operator to use existing value
x = 1
^x = 1 # Works
# ^x = 2 # MatchError
# Ignore values with underscore
{:ok, _} = {:ok, "any value"}
{_, _, third} = {1, 2, 3}
third # => 3
Function Pattern Matching
defmodule Calculator do
def add(a, b), do: a + b
def factorial(0), do: 1
def factorial(n) when n > 0, do: n * factorial(n - 1)
def describe_tuple({:ok, value}) do
"Success: #{value}"
end
def describe_tuple({:error, reason}) do
"Error: #{reason}"
end
def describe_tuple(_) do
"Unknown tuple format"
end
end
# Usage
Calculator.factorial(5) # => 120
Calculator.describe_tuple({:ok, "done"}) # => "Success: done"
Guards in Pattern Matching
defmodule NumberChecker do
def check(x) when is_integer(x) and x > 0 do
"Positive integer"
end
def check(x) when is_integer(x) and x < 0 do
"Negative integer"
end
def check(0), do: "Zero"
def check(x) when is_float(x), do: "Float"
def check(_), do: "Not a number"
end
defmodule Validator do
def valid_email?(email) when is_binary(email) do
String.contains?(email, "@")
end
def valid_email?(_), do: false
def in_range?(num, min, max)
when is_number(num) and num >= min and num <= max do
true
end
def in_range?(_, _, _), do: false
end
Case Statements
defmodule ResponseHandler do
def handle(response) do
case response do
{:ok, data} ->
{:success, data}
{:error, :not_found} ->
{:failure, "Resource not found"}
{:error, :timeout} ->
{:failure, "Request timed out"}
{:error, reason} ->
{:failure, "Error: #{inspect(reason)}"}
_ ->
{:failure, "Unknown response"}
end
end
def parse_number(str) do
case Integer.parse(str) do
{num, ""} -> {:ok, num}
{num, _remainder} -> {:ok, num}
:error -> {:error, "Not a valid number"}
end
end
end
With Statement for Pipeline Pattern Matching
defmodule UserService do
def create_user(params) do
with {:ok, email} <- validate_email(params["email"]),
{:ok, password} <- validate_password(params["password"]),
{:ok, user} <- insert_user(email, password),
{:ok, _} <- send_welcome_email(user) do
{:ok, user}
else
{:error, reason} -> {:error, reason}
_ -> {:error, "Unknown error"}
end
end
defp validate_email(email) when is_binary(email) do
if String.contains?(email, "@") do
{:ok, email}
else
{:error, "Invalid email"}
end
end
defp validate_email(_), do: {:error, "Email required"}
defp validate_password(pass) when is_binary(pass) do
if String.length(pass) >= 8 do
{:ok, pass}
else
{:error, "Password too short"}
end
end
defp validate_password(_), do: {:error, "Password required"}
defp insert_user(email, password) do
{:ok, %{id: 1, email: email}}
end
defp send_welcome_email(_user) do
{:ok, "sent"}
end
end
List Pattern Matching
defmodule ListOps do
def sum([]), do: 0
def sum([head | tail]), do: head + sum(tail)
def first([head | _tail]), do: head
def first([]), do: nil
def second([_, second | _]), do: second
def second(_), do: nil
def take_first_three([a, b, c | _rest]) do
[a, b, c]
end
def take_first_three(list), do: list
def split_at_middle(list) do
middle = div(length(list), 2)
{Enum.take(list, middle), Enum.drop(list, middle)}
end
end
Map Pattern Matching
defmodule UserHandler do
def greet(%{name: name, age: age}) do
"Hello #{name}, you are #{age} years old"
end
def greet(%{name: name}) do
"Hello #{name}"
end
def admin?(%{role: "admin"}), do: true
def admin?(_), do: false
def process_user(%{id: id, name: name} = user) do
# Can use both the whole user and destructured parts
IO.puts("Processing user #{id}: #{name}")
user
end
def update_status(%{status: old_status} = user, new_status) do
%{user | status: new_status}
end
end
defmodule ConfigParser do
def get_database_url(config) do
case config do
%{database: %{host: host, port: port, name: db}} ->
"postgresql://#{host}:#{port}/#{db}"
%{database: %{url: url}} ->
url
_ ->
"postgresql://localhost:5432/default"
end
end
end
Struct Pattern Matching
defmodule User do
defstruct [:id, :name, :email, role: "use
Установить elixir-pattern-matching в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
BashReadFAQ
Что делает скилл elixir-pattern-matching?
Use when Elixir pattern matching including function clauses, case statements, with statements, and destructuring. Use for elegant control flow.
Как установить скилл elixir-pattern-matching?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл elixir-pattern-matching запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic