Elixir - Cond Statement


Advertisements

Cond statements are used where we want to execute a code on the basis of several conditions. It works like an if….else construct in several other programming languages.

Syntax

The syntax of a cond statement is as follows −

cond do
   boolean_expression_1 -> #Execute if this condition is true
   boolean_expression_2 -> #Execute if this condition is true
   ...
   true -> #Execute if none of the above conditions are true
end

If any of the boolean_expression Boolean expressions evaluates to true, then the block of code inside the statement will be executed.

The way cond statement works is − it will start from the first condition and check if it is true. If true, it will execute the code corresponding to that condition, otherwise, it will move on to the next condition. It will repeat this till a condition matches. If no condition matches, it raises a CondClauseError, i.e., the condition clause was not satisfied. To prevent this, a true statement should always be used at the end of a cond statement.

Example

guess = 46
cond do
   guess == 10 -> IO.puts "You guessed 10!"
   guess == 46 -> IO.puts "You guessed 46!"
   guess == 42 -> IO.puts "You guessed 42!"
   true        -> IO.puts "I give up."
end

The above program generates the following result −

You guessed 46!
elixir_decision_making.htm
Advertisements