Aleksandarf
Aleksandarf

Reputation: 403

Elixir, unpacking argument from list or tuple

I would like to get the following to run

def myfunction(a, b) do
    IO.puts "Success"
end

def runstuff do
    jobs = {&myfunction/2, [1, 3]}
    {to_run, args} = jobs
    to_run.(args) # broken code
end

Well, the code above is broken but I think shows what I would like to achieve, I'm a happy Elixir newbie (apparently :)) I'm hoping that it can be solved with some elixir macro magic. Edit: moved in jobs according to comment.

Upvotes: 2

Views: 4812

Answers (2)

I suspect your real example involves a much longer list of args, but this is how to get your example to work.

def myfunction(a, b) do
    IO.puts "Success"
end

def runstuff do
    jobs = {&myfunction/2, [1, 3]}
    {to_run, [a, b]} = jobs
    to_run.(a,b) # unbroken code
end

Upvotes: 0

Paweł Dawczak
Paweł Dawczak

Reputation: 9639

What you might want to take a look is Kernel.apply/3.

This is pattern known as MFA: Module, Function, Arguments. This requires your functions to be defined in some module.

Please consider following example:

defmodule Fun do
  def myfunction(a, b) do
    IO.puts "Success, a: #{a}, b: #{b}"
  end

  def runstuff do
    jobs = {Fun, :myfunction, [1, 3]}
    {m, f, a} = jobs
    apply(m, f, a)
  end
end

Fun.runstuff

So:

▶ elixir fun.exs
Success, a: 1, b: 3

Upvotes: 8

Related Questions