...

/

Control Flow with Functions

Control Flow with Functions

Learn to use pattern matching with functions to control program flow.

Introduction to control flow with functions

Programs typically cover a variety of scenarios, and we need to create code to handle each one. Pattern matching and functions are the fundamental tools we use to control the program flow in functional programming.

Until now, we’ve used pattern matching with the = operator to make two things match. It’s useful for making sure our program runs in an expected scenario. When the match is not possible, Elixir raises an error and stops the program process. When we use pattern matching with functions, we can do more than throw errors, which we’ll discuss in this section.

Using pattern matching with functions

Let’s create a simple program that will say which of two given numbers is greater. If the numbers are equal, we can show either one of them. For this example, we’ll use named functions, then create the file number_compare.ex:

defmodule NumberCompare do
  def greater(number, other_number) do
    check(number >= other_number, number, other_number)
  end

  defp check(true, number, _), do: number
  defp check(false, _, other_number), do: other_number 
end

We have new things here: multiple function definitions with the same name, some defined with a defp directive, and others with values in the arguments. Don’t worry about those details ...