Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
About the Author
About the Reviewers

Using guard clauses and pattern matching in function definitions

In the Using pattern matching recipe in Chapter 2, Data Types and Structures, we saw how it was possible to use the = operator to match values on the right-hand side with values on the left-hand side. In this recipe, we will see pattern matching in action without using the = operator. We will use pattern matching implicitly in function definitions with the same name and arity, and Elixir will use it to determine which function version to execute.

Sometimes, pattern matching is not enough to determine which function to execute, so we will also be using guard clauses in our function definitions. Guard clauses allow us to only execute a given function if some condition regarding its argument types or values is verified.

Getting ready

This is how we get started:

  1. Define a new module named PatternsAndGuards in a file named patterns_and_guards.ex by inserting the following code:

    defmodule PatternsAndGuards do
      #pattern matching...