Invoke Elixir Functions with Apply
I had a weird problem yesterday: I wanted to pass a function into another function and then invoke it, all for the sake of a friendly API.
Elixir's apply
to the rescue. Here's the rough implementation.
defmodule Example do
def do_things(index, rotation, operator) do
apply(Kernel, operator, [index, rotation])
end
end
iex> Example.do_things(10, 20, :+)
30
iex> Example.do_things(10, 20, :-)
-10
apply
also accepts your own functions:
defmodule Example do
def do_things(index) do
apply(__MODULE__, :make_bigger, [index])
end
def make_bigger(a) do
a * 10000
end
end
iex> Example.do_things(100)
1000000
The module name (Example
) will work in place of __MODULE__
, if you prefer. This seems like a pretty powerful feature.