Elixir语言速查
管道操作符
" HELLO "
|> String.trim()
|> String.downcase()
|> String.split(" ")
[1, 2, 3, 4, 5]
|> Enum.filter(&(rem(&1, 2) == 0))
|> Enum.map(&(&1 * 10))
|> Enum.sum() # 60
模式匹配
# 基本匹配
{:ok, result} = {:ok, 42}
[head | tail] = [1, 2, 3]
# 函数子句
defmodule Math do
def factorial(0), do: 1
def factorial(n) when n > 0, do: n * factorial(n - 1)
end
# case 表达式
case File.read("file.txt") do
{:ok, content} -> process(content)
{:error, reason} -> IO.puts("Error: #{reason}")
end
并发(进程)
# 生成进程
pid = spawn(fn -> IO.puts("Hello from process") end)
# 发送和接收消息
send(pid, {:message, "hello"})
receive do
{:message, msg} -> IO.puts("Got: #{msg}")
after 5000 -> IO.puts("Timeout")
end
# Task(异步操作)
task = Task.async(fn -> heavy_computation() end)
result = Task.await(task, 10_000)
GenServer 示例
defmodule Counter do
use GenServer
def start_link(initial), do: GenServer.start_link(__MODULE__, initial)
def increment(pid), do: GenServer.cast(pid, :increment)
def get(pid), do: GenServer.call(pid, :get)
@impl true
def init(state), do: {:ok, state}
@impl true
def handle_cast(:increment, state), do: {:noreply, state + 1}
@impl true
def handle_call(:get, _from, state), do: {:reply, state, state}
end
Mix 命令
| 命令 | 说明 |
|---|---|
| mix new app_name | 创建新项目 |
| mix deps.get | 安装依赖 |
| mix compile | 编译项目 |
| mix test | 运行测试 |
| iex -S mix | 交互式 REPL |