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
为避免返回值为 nil
和 false
,需添加一个默认返回值,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/2
、unless/2
注意⚠️: 在case、cond、if、unless为内部作用域,内部作用域内操作外部变量,不会改变外部变量的值。