Elixir cond do

elixir, cond, filter – Aug 15 2019

This blog post looks into the minor differences between using cond vs case within Elixir.

• • •

The 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"

For illustration purposes the elixir code posted above would translate into something like this in javascript.

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"
 "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 cond/1.

Another way of looking at this is you could write multiple if else statements.

If all the conditions return false or nil a (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.

Follow on Twitter
Follow on Github