Understanding Variables Scopes in Elixir

Hi,
I’m wondering as to why I get this error, shown below:

However, when I define the variable hours = 8.0 inside the daily_rate(hourly_rate) function inside the FreelancerRates module, the error is resolved.

Can someone please explain, this behavior.

Thanks in advance! :grin:

From https://elixir-lang.readthedocs.io/en/latest/technical/scoping.html:

According to the rules of lexical scope, any variables defined in the surrounding scope are accessible in all other scopes it contains.

In Figure 1 above, any variable defined in the top level scope will be accessible in the module’s scope and any scope nested inside it, and so on.

There is an exception to this rule which applies only to named functions: any variable coming from the surrounding scope has to be unquoted inside a function clause body.

To see how that works check https://elixir-lang.readthedocs.io/en/latest/technical/scoping.html#named-functions-and-modules

Quoting from the link above again:

defmodule M do
  a = 1

  # 'a' inside unquote() unambiguously refers to 'a' defined
  # in the module's scope
  def a, do: unquote(a)

  # 'a' inside the body unambiguously refers to the function 'a/0'
  def a(b), do: a + b
end

M.a          #=> 1
M.a 3        #=> 4

In any way, I think you want to define a constant. The Elixir version of that are module attributes, see https://elixir-lang.org/getting-started/module-attributes.html.

Hope that helps. :)

1 Like

Hi @fap,
Exactly, I was looking to define them as constants within the module; @module_attributes worked.

I’ll also look into the scoping rules in Elixir, in the link you provided.

Thanks for your time. :pray:

SJ-Nosrat,

Perhaps also see syntax - What does "@" do in Elixir? - Stack Overflow