O'Reilly logo

Elixir Cookbook by Paulo A Pereira

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

Note

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
[Defaults] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required