码迷,mamicode.com
首页 > 其他好文 > 详细

elixir 模式匹配

时间:2015-03-17 20:09:58      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

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}

 

elixir 模式匹配

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!