Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the double backslash mean in a function parameter in Elixir?

Tags:

elixir

I recently came across a code snippet such as:

def loop(ring_pid \\ self, nil, true) do
  #some code 
end

What do the double backslashes mean? I googled around and found http://elixir-lang.org/getting-started/sigils.html, but that applies to regular expressions not function params.

like image 944
Nona Avatar asked Jan 02 '16 08:01

Nona


2 Answers

It specifies a default value.

Function arguments defined using \\ after the argument name are providing an optional default. So if loop/2 is called, the first argument will be the pid returned from self(). If loop/3 is called, then you would specify a pid.

Let's take another (trivial) example:

math.ex

defmodule Math do   
  def add(a \\ 2, b) do
    a + b   
  end 
end

iex (1)> c("math.ex")

iex (2)> Math.add(1, 8) # add/2, because you are matching 1 to `a`.
9

iex (3)> Math.add(8) # add/1, because `a` is by default matched to 2.
10
like image 195
ham-sandwich Avatar answered Oct 06 '22 07:10

ham-sandwich


\\ is used to define default params, source

You can observe that behavior by trying it in the iex console, for instance:

defmodule Foo do
  def bar(x \\ 1, y) do
    x * y
  end
end

Foo.bar(2,3) # => 6
Foo.bar(3) # => 3
like image 40
arathunku Avatar answered Oct 06 '22 08:10

arathunku