Basics
Elixir If and Unless
Conditional Statements
Elixir if and unless control flow with pattern matching.
Understanding the "if" Control Structure
The if control structure in Elixir functions similarly to other programming languages. It evaluates a condition and executes the code block if the condition is true
. The if
statement can also include an else
block that runs if the condition is false
.
Here's an example that checks whether a number is positive:
Introducing the "unless" Control Structure
The unless control structure is the opposite of if
. It executes the code block only if the condition is false
. Similar to if
, it can include an else
block that runs if the condition is true
.
Consider this example where we check if a user is not an admin:
Pattern Matching with If and Unless
In Elixir, pattern matching is a powerful feature that can be used within if
and unless
statements to match values against patterns. This allows for more complex conditional checks.
In this example, the if
statement checks if value
matches the tuple {:ok, message}
. If it matches, it executes the block and binds message
to the string "Success".
Summary
Elixir's if
and unless
control structures provide flexible and readable ways to handle conditional logic. By combining them with pattern matching, you can create powerful and expressive conditions in your code.