elixir 模式匹配

elixir 模式匹配刚接触还是有点不习惯,在Elixir里,=操作符被称为匹配操作符

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

1=x 合法 左右都等于1

2=x 两侧不相等时,会导致一个MatchError错误

匹配列表

iex(2)> a = [1]
[1]
iex(3)> [h|t] = a
[1]
iex(4)> h
1
iex(5)> t
[]

用[h|t] = a ---》[h|t]=[1]--》h 匹配到1  t为空

如果 [h|t] = []

** (MatchError) no match of right hand side value: []

匹配元组

iex(35)> {a, b, c} = {:hello, "word", 33}
{:hello, "word", 33}
iex(36)> a
:hello
iex(37)> b
"word"
iex(38)> c
33

两边不匹配

iex(39)> {a, b, c} = {:hello, "word"}
** (MatchError) no match of right hand side value: {:hello, "word"}

右侧第一个不是 :ok 也不匹配

iex(40)> {:ok, result} = {:ok, 13}
{:ok, 13}
iex(41)> result
13
iex(42)> {:ok, result} = {:error, :oops}
** (MatchError) no match of right hand side value: {:error, :oops}

原文地址:https://www.cnblogs.com/jasonduan/p/4345205.html