elixir 模式匹配刚接触仍是有点不习惯,在Elixir
里,=
操做符被称为匹配操做符ide
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: 1oop
1=x 合法 左右都等于1code
2=x 两侧不相等时,会致使一个MatchError
错误error
匹配列表elixir
iex(2)> a = [1]
[1]
iex(3)> [h|t] = a
[1]
iex(4)> h
1
iex(5)> t
[]word
用[h|t] = a ---》[h|t]=[1]--》h 匹配到1 t为空co
若是 [h|t] = []习惯
** (MatchError) no match of right hand side value: []错误
匹配元组ps
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)> result13iex(42)> {:ok, result} = {:error, :oops}** (MatchError) no match of right hand side value: {:error, :oops}