Reference module function using a variable

Hi there,

I am just wondering how would it be possible to capture a module function using variables.

Here is a code example:

  defp new_actuator(name, module) do
    %Actuator{:id => actuator_id(name), :function => &}

If I test the following using a1 = new_actuator(xor_score, TestActuators), I would get the following.

     Assertion with == failed
     code:  assert a1.function == &TestActuators.xor_score/2
     left:  &
     right: &TestActuators.xor_score/2

How can I pass this test using variables to capture the function?

This would work, but it is not very elegant (and is not passing the test above).

  defp new_actuator(name, module) do
    fun = fn signal, state -> apply(module, name, [signal, state]) end
    %Actuator{:id => actuator_id(name), :function => fun}

Best regards, Borja

Unfortunately you need to use Function.capture(mod, name, arity) as Elixir cannot deduce that name is a variable, not actual function name.

Hi hauleth,
fun = Function.capture(module, function_name, 2) does actually the trick very very well. Thank you!

  defp new_actuator(function_name, module) do
    fun = Function.capture(module, function_name, 2)
    %Actuator{:id => actuator_id(function_name), :function => fun}

Is passing the test.