Cond
Useful to make multi conditions with different values and return the first that match true
cond do
2 + 2 == 5 ->
"This will not be true"
2 * 2 == 3 ->
"Nor this"
1 + 1 == 2 ->
"But this will"
endcond do
2 + 2 == 5 ->
"This will not be true"
2 * 2 == 3 ->
"Nor this"
1 + 1 == 2 ->
"But this will"
end"But this will""But this will"This is equivalent to else if clause in many imperative languages (used much less here)
Is necessary add a final condition equal true, which always will match, because if all the conditions return nil of falsean error CondClauseError is raised
cond do
2 + 2 == 5 ->
"This is never true"
2 * 2 -> 3
"Nor this"
true ->
"This is always true, equivalent to else"
endcond do
2 + 2 == 5 ->
"This is never true"
2 * 2 -> 3
"Nor this"
true ->
"This is always true, equivalent to else"
end"This is always true, equivalent to else""This is always true, equivalent to else"cond considers any value besides nil or false to be true
cond do
hd([1, 2, 3]) -> "1 is considered as true"
endcond do
hd([1, 2, 3]) -> "1 is considered as true"
end"1 is considered true""1 is considered true"If/Unless
Elixir provide macros if/2 and unless/2 which are useful when you need to check for only on condition
if
if true do
"This works!"
endif true do
"This works!"
end"This works!""This works!"unless
unless true do
"This is will never be seen"
endunless true do
"This is will never be seen"
endnilnilThey also support else
if nil do
"This won't be seen"
else
"This will"
endif nil do
"This won't be seen"
else
"This will"
end"This will""This will"do/end blocks
iex> if true, do: 1 + 2
2
iex> if false, do: :this, else: :that
:thatiex> if true, do: 1 + 2
2
iex> if false, do: :this, else: :that
:thatThese are equivalent:
code/1
if true do
a = 1 + 2
a + 10
endif true do
a = 1 + 2
a + 10
endcode/2
if true, do: (
a = 1 + 2
a + 10
)if true, do: (
a = 1 + 2
a + 10
)out/all
13
referencies
Elixir Conditions: https://elixir-lang.org/getting-started/case-cond-and-if.html [archive]

