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"
end
"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"
end
"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"
end
"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!"
end
"This works!"

unless

unless true do
  "This is will never be seen"
end
nil

They also support else

if nil do
  "This won't be seen"
else
  "This will"
end
"This will"

do/end blocks

iex> if true, do: 1 + 2
2
iex> if false, do: :this, else: :that
:that

These are equivalent:

code/1

if true do
  a = 1 + 2
  a + 10
end

code/2

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]