Hai Hoang
Hai Hoang

Reputation: 1257

Elixir: functions call with underscore and assignment as parameters

What is the purpose of using _a = 5 instead of 5 in the code below? Is there a name for this technique?

def some_func(a) do
    IO.puts(a)
end

some_func(_a = 5)

Upvotes: 1

Views: 212

Answers (3)

Adam Millerchip
Adam Millerchip

Reputation: 23091

This is described in the Naming Conventions:

Underscore (_foo)

Elixir relies on underscores in different situations.

For example, a value that is not meant to be used must be assigned to _ or to a variable starting with underscore:

iex> {:ok, _contents} = File.read("README.md")

There is a video of José Valim doing it here:

https://www.youtube.com/watch?v=1rFlhFbJ1_s&t=246s

He's writing the following Enum.reduce/3 call:

|> Enum.reduce({_depth = 0, _position = 0}, fn 
  {:forward, value} -> {depth, position} -> {depth, position + value}
  ...
end

Here the initial value of the accumulator is written as {_depth = 0, _position = 0}. The _depth and _position variables are not used, they are just hints to the developer. He could have written {0, 0} directly instead, but then it wouldn't be obvious what the integers referred to without checking the function implementation below.

Upvotes: 3

7stud
7stud

Reputation: 48599

Sometimes I use that technique in this situation:

defmodule A do
  def compute(list, x), do: _compute(list, x, [])

  defp _compute([head|tail], x, acc) do
    #
    val = ...
    _compute(tail, x, [val|acc]) 
  end
end

and I'll write:

                                                |
                                                |
defmodule A do                                  V
  def compute(list, x), do: _compute(list, x, _acc=[])

in order to indicate to a beginner what the [] is. But, in the example you posted where there is only one parameter variable, I don't think it clarifies anything.

Upvotes: 1

Evaldo Bratti
Evaldo Bratti

Reputation: 7658

I think what is happening there is just a pattern matching between _a and 5 before properly calling some_func

the result of _a = 5 is 5.

the same happens with a = 5 which is also 5

and even for 5 = 5, you guessed right, it is 5.

so at the execution time what happens is

some_func(_a = 5) 
some_func(5)

Though this pre _ usage is discouraged, besides in function declarations, as it's used to tell the compiler that the variable is indeed not used in the function body.

Upvotes: 1

Related Questions