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

Defining functions with default arguments

In Elixir, named functions (defined with the def macro) can accept arguments and sometimes, it is convenient to assume them as optional by defining a default value or expression. Default values for function arguments are defined using \\ after the argument name.


If we define a foo(a, b, c \\ 0) function and c has a default value, although the function can be invoked as foo(1,3) with arity 2, the function foo/3 is executed, in this case, as foo(1,3,0). We don't explicitly pass a value for c but it will take the defined value, in this case, 0.

Getting ready

Load the Defaults file module inside IEx and open the file defining the module (defaults.ex) inside your favorite code editor:

> iex defaults.ex

How to do it…

To define functions with default arguments, follow these steps:

  1. Define a sum function in the Defaults module by adding the following code to defaults.ex:

    def sum(a, b \\ 1, c \\ 1) do
      a + b + c
  2. Save the file and reload it...