
- Elixir Tutorial
- Elixir - Home
- Elixir - Overview
- Elixir - Environment
- Elixir - Basic Syntax
- Elixir - Data Types
- Elixir - Variables
- Elixir - Operators
- Elixir - Pattern Matching
- Elixir - Decision Making
- Elixir - Strings
- Elixir - Char Lists
- Elixir - Lists and Tuples
- Elixir - Keyword Lists
- Elixir - Maps
- Elixir - Modules
- Elixir - Aliases
- Elixir - Functions
- Elixir - Recursion
- Elixir - Loops
- Elixir - Enumerables
- Elixir - Streams
- Elixir - Structs
- Elixir - Protocols
- Elixir - File I/O
- Elixir - Processes
- Elixir - Sigils
- Elixir - Comprehensions
- Elixir - Typespecs
- Elixir - Behaviours
- Elixir - Errors Handling
- Elixir - Macros
- Elixir - Libraries
- Elixir Useful Resources
- Elixir - Quick Guide
- Elixir - Useful Resources
- Elixir - Discussion
Elixir - Cond Statement
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!