Question

I want to choose the routine of the program in run time. I couldn't find any function pointer type (or a reference to a method) in Elixir.

defmodule MyModule do
    def method do
        choice()
    end
end

I want to give a method to choose at run time. How to do this?

Was it helpful?

Solution

You can send in a function as parameter and then call that function (with .(...)) like this:

iex> defmodule MyModule do
   >     def my_method(choice) do
   >         choice.("hello")
   >     end
   >  end

and then call it by using & before the module name like:

iex> MyModule.my_method(&String.upcase/1)
"HELLO"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top