Elixir - case, cond, and if

case

case 允许我们在多个条件中,选取一个与参数匹配的项。匿名函数也可以完成域case相同的功能

iex(13)> case {1, 2, 3} do
...(13)> {1, x, 3} when  x > 0 ->
...(13)> "Will match"
...(13)> _ -> "Would match, if guard condition were not satisfied"
...(13)> end
"Will match"
iex(14)> 

cond
当我们需要检查不同条件并且找到第一个结果不是 nil 或是 false 的值,在这种条件下, 使用 cond
为避免返回值为 nilfalse,需添加一个默认返回值,ture 时的状态

iex> cond do
...>   2 + 2 == 5 ->
...>     "This is never true"
...>   2 * 2 == 3 ->
...>     "Nor this"
...>   true -> # 除了 nil 和 false 任何值cond都认为为 true
...>     "This is always true (equivalent to else)"
...> end
"This is always true (equivalent to else)"

if and unless

当我们只需要检查一个条件是否符合要求时,可以使用 if/2unless/2

注意⚠️: 在case、cond、if、unless为内部作用域,内部作用域内操作外部变量,不会改变外部变量的值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值