...

/

Elixir Control-Flow Structures

Elixir Control-Flow Structures

Learn about Elixir's built-in control-flow structures.

Introduction to control-flow structures

Working with functional programming, we use function clauses to control the flow of the program. Elixir’s built-in control-flow structures, such as case, cond, if, and unless, help us develop features quickly. We’ll see how each one can be useful and how it works.

case: control with pattern matching

The case structure is useful when we want to check an expression with multiple pattern matching clauses. It helps deal with functions that may have an unexpected effect. To see how it works, we’ll change our script that calculates the abilities modifier for RPG players:

user_input = IO.gets "Write your ability score:\n" 
case Integer.parse(user_input) do
  :error -> IO.puts "Invalid ability score: #{user_input}" 
  {ability_score, _} ->
    ability_modifier = (ability_score - 10) / 2
    IO.puts "Your ability modifier is #{ability_modifier}" 
end

We can run it with the elixir ability_modifier.exs command and interact with it:

❮ Write your ability score: ➾ hot dogs
❮ Invalid ability score: hot dogs

We used case to handle two scenarios: one in which the user input is a valid number, and the other in which the user provides ...