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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值