Elixir Decision Making

Welcome to a tutorial on Elixir. Here you will learn about decision Making in Elixir.

Decision-making structures need programmers to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Check out the diagram below of a typical decision-making structure found in most programming languages.

 

Decision-making statements

If/else conditional constructs are provided in Elixir just like other programming languages. Also, Elixir has a cond statement that calls the first true value it finds. The case is another control flow statement that makes use of pattern matching to control the flow of the program.

The table below is a brief description of the types of decision-making statements provided by Elixir.

Sr.No.Statement & Description
1

The ‘if statement’

An if statement typically consists of a Boolean expression followed by doing, one or more executable statements, and finally an end keyword. The code in the if statement executes only if the Boolean condition evaluates to true.

2

The ‘if..else statement’

An if statement can be followed by an optional else statement (that is, within the do..end block), which executes when the Boolean expression is false.

3

The ‘unless statement’

The unless the statement has the same body as an if statement. The code within the unless statement executes when the condition specified is false only.

4

The ‘unless..else statement’

The unless..else statement has the same body as an if..else statement. The code within the unless statement executes when the condition specified is false only.

5

The ‘cond’

The cond statement is used when we want to execute code on basis of several conditions. This works like an if...else if….else construct in several other programming languages.

6

The ‘case’

The case statement can be considered as a replacement for the switch statement in imperative languages. The case takes a variable/literal and applies pattern matching to it with different cases. Also, if any case matches, Elixir executes code associated with that case and exits the case statement.