What is a case statement in Elixir?
The Elixir programming language has several control structures that determine the execution flow in the program. These control structures are used to make decisions, repeat operations, and determine the order in which statements or code blocks are executed. In Elixir, the case statement compares an expression value against multiple patterns. It evaluates code blocks from top to bottom until the pattern matches the given value.
Syntax
The basic syntax of the case statement to execute different code blocks based on pattern matching is given below :
case expression dopattern1 -># If expression matches with the pattern 'pattern1', this code block will executedpattern2 -># If expression matches with the pattern 'pattern2', this code block will executed_ -># If no expression matches with the patterns, this code block will executedend
In the code above, the case keyword is used, followed by the expression to be evaluated.
pattern1andpattern2: These are patterns to be matched against the expression.–>: This is used to distinguish between the pattern and the code block to be executed._: When none of the above patterns match, the code inside this block will execute.
Flowchart
The following diagram illustrates the flow of control of a case statement in Elixir:
Code example 1
The case statement can be used to match against a specific value of an expression.
day = 0 # change this value to see different resultcase day do1 -> IO.puts("Mon")2 -> IO.puts("Tue")3 -> IO.puts("Wed")4 -> IO.puts("Thur")5 -> IO.puts("Fri")6 -> IO.puts("Sat")_ -> IO.puts("Sun")end
Code explanation
Line 1: We define and declare the
dayvariable.Line 2: The
dayvariable is passed to thecasestatement, and its value is evaluated.Lines 3–8: The different cases are defined.
Line 9: If none of the cases match, the code inside
_will get executed.
Code example 2
Let’s see another example of a case statement that evaluates the expression against a range of values. This approach allows us to take different actions based on where the expression falls within those predefined ranges.
marks = 65case marks domarks when marks > 100 -> IO.puts("Must be in range 0-100")marks when marks < 0 -> IO.puts("Must be in range 0-100")marks when marks < 50 -> IO.puts("Fail")marks when marks < 60 -> IO.puts("Average")marks when marks < 70 -> IO.puts("Good")marks when marks <= 80 -> IO.puts("Excellent")_-> IO.puts("Outstanding")end
Code explanation
Line 1: We define and declare the
marksvariable.Line 2: The
marksvariable is passed to thecasestatement, and its value is evaluated.Lines 3–8: The different patterns are defined.
Line 9: If none of the cases match, the code inside
_will get executed.
In Elixir, the case statement is a flexible and powerful control structure that efficiently manages values and pattern-matching. It can work with custom-defined patterns and complex data structures.
Free Resources