Elixir,从列表或元组中解包参数

Elixir, unpacking argument from list or tuple

我想收到以下内容 运行

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

好吧,上面的代码已损坏,但我认为显示了我想要实现的目标,我是一个快乐的 Elixir 新手(显然 :))我希望它可以通过一些 elixir 宏魔法来解决。 编辑:根据评论移动工作。

您可能想看的是 Kernel.apply/3

这是称为 MFA 的模式:ModuleFunctionArguments。这需要在某些模块中定义您的函数。

请考虑以下示例:

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

所以:

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

我怀疑您的真实示例涉及更长的参数列表,但这是让您的示例正常工作的方法。

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