Learn With Me: Elixir - Default Values and Multiple Function Clauses (#25)

When you have multiple function clauses that have the same number of parameters and one (or more) of the parameters has a default value, what do you do? Do you put the default value in both function clauses?

That seems like the logical thing to do, but Elixir actually wants you to specify a special function head that contains the parameter values. This is a function clause without a body. Once that special function head is in place, the other function clauses can be specified without any default values at all. The default values from the special function head will apply to all the other clauses.

Let's look at an example.

def do_something(param1, param2 \\ 3)

def do_something(param1, param2) when is_integer(param1) do
	{param1 * 10, param2}
end

def do_something(param1, param2) when is_float(param1) do
	{param1 * 100, param2}
end

In the above example, there are two function clauses for the do_something/2 function that multiply the first parameter by 10 and then package it with a second parameter into a tuple.

In order to specify a default value for these functions, we don't put the default value in both function clauses, but rather we create a new function clause that just has the default values and no function body. These default values will then apply to the other function clauses of the same arity. Elixir only wants one set of default values per function.

You can find these functions in a module in the code examples in the Learn With Me: Elixir repository on Github so that you can load it into IEx and use it. They are in the "multi_clause_default.exs" file under the "lwm 25 - Default Values and Multiple Clauses" folder.

Let's look at what it looks like when we use the do_something/2 function.

iex> MultiClauseDefault.do_something(3, 3)
{30, 3}
iex> MultiClauseDefault.do_something(3.4, 3)
{340.0, 3}
iex> MultiClauseDefault.do_something(4, 10)
{40, 10}
iex> MultiClauseDefault.do_something(4)
{40, 3}
iex> MultiClauseDefault.do_something(3.14)
{314.0, 3}

That's it! This was a short one today.