Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to __MODULE__ for named functions in Elixir/ Erlang?

Tags:

erlang

elixir

Is there an equivalent for retrieving the name of a function just like like __MODULE__ retrieves the name of a Module in Elixir/Erlang?

Example:

defmodule Demo do
  def home_menu do
    module_name = __MODULE__
    func_name = :home_menu 
    # is there a __FUNCTION__
  end
End

EDITED

The selected answer works,

but calling the returned function name with apply/3 yields this error:

[error] %UndefinedFunctionError{arity: 4, exports: nil, function: :public_home, module: Demo, reason: nil}

I have a function :

defp public_home(u, m, msg, reset) do

end

The function in question will strictly be called within its module.

Is there a way to dynamically call a private function by name within its own module?

like image 591
Charles Okwuagwu Avatar asked Nov 14 '17 08:11

Charles Okwuagwu


People also ask

What is __ module __ In Elixir?

__MODULE__ is a compilation environment macros which is the current module name as an atom. Now you know alias __MODULE__ just defines an alias for our Elixir module. This is very useful when used with defstruct which we will talk about next.

How do you define a function in Elixir?

Named Functions. An Elixir function is typically named, and is called a "named function". Functions are defined with the def keyword followed by a parameter list. A function also has a body containing the contents of the function. Like modules, the function body begins with the do keyword and ends with the end keyword.

What does |> mean in Elixir?

This is the pipe operator. From the linked docs: This operator introduces the expression on the left-hand side as the first argument to the function call on the right-hand side. Examples.

How do you get variable type in Elixir?

Starting in elixir 1.2 there is an i command in iex that will list the type and more of any Elixir variable. If you look in the code for the i command you'll see that this is implemented via a Protocol.


1 Answers

▶ defmodule M, do: def m, do: __ENV__.function  
▶ M.m                                                 
#⇒ {:m, 0}

Essentially, __ENV__ structure contains everything you might need.

like image 163
Aleksei Matiushkin Avatar answered Oct 09 '22 20:10

Aleksei Matiushkin