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}