venomnert

venomnert

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

First Post!

idi527

idi527

:waving_hand:

What do you consider to be variables in your snippet?

Most Liked

LostKobrakai

LostKobrakai

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.

Last Post!

venomnert

venomnert

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

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New

Other popular topics Top

grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54260 488
New
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 44778 311
New

We're in Beta

About us Mission Statement