Today I Learned

hashrocket A Hashrocket project

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.

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.