Case
case {1, 2, 3} do
{1, _x, 3} ->
"This clause will match and bind _x to 2 in this clause"
{4, 5, 6} ->
"This clause won't match"
_ ->
"This clause would match any value"
end
case {1, 2, 3} do
{1, _x, 3} ->
"This clause will match and bind _x to 2 in this clause"
{4, 5, 6} ->
"This clause won't match"
_ ->
"This clause would match any value"
end
"This clause will match and bind _x to 2 in this clause"
"This clause will match and bind _x to 2 in this clause"
To use pattern match you need to use pin^
operator
x = 1
case 10 do
^x -> "Won't match"
_ -> "Will match"
end
x = 1
case 10 do
^x -> "Won't match"
_ -> "Will match"
end
"Will match"
"Will match"
Clause allow extra conditions to be specified via guards
case {1, 2, 3} do
{1, x, 3} when x > 0 ->
"Will match"
_ ->
"Would match, if guard condition were not satisfied"
end
case {1, 2, 3} do
{1, x, 3} when x > 0 ->
"Will match"
_ ->
"Would match, if guard condition were not satisfied"
end
"Will match"
"Will match"
Erros in guards will not leak but simply make the guard fail
iex> hd(1)
** (ArgumentError) argument error
:erlang.hd(1)
iex> hd(1)
** (ArgumentError) argument error
:erlang.hd(1)
case 1 do
x when hd(x) -> "Won't match"
x -> "Got #{x}"
end
case 1 do
x when hd(x) -> "Won't match"
x -> "Got #{x}"
end
"Got 1"
"Got 1"
Anonymous Functions can also have multiple clauses and guards
f = fn
x, y when x > 0 -> x + y
x, y -> x * y
end
f = fn
x, y when x > 0 -> x + y
x, y -> x * y
end
iex> f.(1, 3)
4
iex> f.(-1, 3)
-3
iex> f.(1, 3)
4
iex> f.(-1, 3)
-3
referencies
Elixir Conditions: https://elixir-lang.org/getting-started/case-cond-and-if.html [archive ]