Named functions and scopes

Would someone explain the following snippet of code

defmodule P do
  def f, do: "I am P's f"
  def g, do: f
end
iex> P.g
"I am P's f"

When I looked into it seems that ‘f’ inside of g/0 get’s treated as a function. However, how does f() become available to g/0. I thought named functions can’t access variables outside their scope unless unquote is used

:wave:

What do you consider to be variables in your snippet?

The ‘f’ inside of g/0

I think it’s a function invocation.

defmodule P do
  def f, do: "I am P's f"
  def g, do: f()
end

The parenthesis on zero-arity function calls are optional even though it’s discouraged to skip them.

2 Likes

Yep, that’s correct. I was able to confirm this over at Elixir Slack.
def g, do: f equals def g, do: P.f()