Elixir cond do
This blog post looks into the minor differences between using cond vs case within Elixir.
• • •
cond/1 can be not so obvious when you know that a
case/1 statement is available. The difference between the two is obvious once you see examples.
Elixir evaluates the cond and if statements on the basis of truthiness. All values are considered to be true except nil and false.
def sample(item) do cond do item == "hello" -> "We have Hello" is_list(item) -> "We have a list parameter" is_atom(item) -> "We have an atom passed in" true -> "We have something we don't know" end end
if (item == "hello") "We have Hello" else if (is_list(item)) "We have a list parameter" else if (is_atom(item)) "We have an atom passed in" else "We have something we don't know"
In situations when you want to run multiple checks looking for something to be true you would best use a
Another way of looking at this is you could write multiple
if else statements.
If all the conditions return
(CondClauseError) is raised but you can make the last statement true as shown above if you need some default statement.
An excellent discussion goes into details on what the community thinks.