Elixir - Decision Making


Advertisements

Decision making structures require that the programmer specifies 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.

Following is the general from of a typical decision making structure found in most of the programming language −

Decision Making

Elixir provides if/else conditional constructs like many other programming languages. It also has a cond statement which calls the first true value it finds. Case is another control flow statement which uses pattern matching to control the flow of the program. Let's have a deep look at them.

Elixir provides the following types of decision making statements. Click the following links to check their detail.

Sr.No. Statement & Description
1 if statement

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

2 if..else statement

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

3 unless statement

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

4 unless..else statement

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

5 cond

A cond statement is used where we want to execute code on basis of several conditions. It kind of works like an if...else if….else construct in several other programming languages.

6 case

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

Advertisements