Elixir-模式匹配

模式匹配是 Elixir 很强大的特性,它允许我们匹配简单值、数据结构、甚至函数。

匹配操作符

Elixir 中, = 操作符就是我们的匹配操作符。通过这个匹配操作符,我们可以赋值和匹配。

iex> x = 1
1

现在做一些简单的匹配

iex> 1 = x
1
iex> 2 = x
** (MatchError) no match of right hand side value: 1

# Lists
iex> list = [1, 2, 3]
iex> [1, 2, 3] = list
[1, 2, 3]
iex> [] = list
** (MatchError) no match of right hand side value: [1, 2, 3]

iex> [1 | tail] = list
[1, 2, 3]
iex> tail
[2, 3]
iex> [2|_] = list
** (MatchError) no match of right hand side value: [1, 2, 3]

# Tuples
iex> {:ok, value} = {:ok, "Successful!"}
{:ok, "Successful!"}
iex> value
"Successful!"
iex> {:ok, value} = {:error}
** (MatchError) no match of right hand side value: {:error}

Pin 操作符

当匹配的左边包含变量的时候,匹配操作符同时会做赋值操作。有些时候,这种行为并不是预期的,这种情况下,我们可以使用 ^ 操作符。

iex> x = 1
1
iex> ^x = 2
** (MatchError) no match of right hand side value: 2
iex> {x, ^x} = {2, 1}
{2, 1}
iex> x
2
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容