Elixir 中有 splat 运算符吗?

Is there a splat operator in Elixir?

defmodule UnixCommands do
    alias Porcelain.Result
        def run(command, *opts) do
             %Result{out: output, status: _} = Porcelain.exec(command, [opts])
             IO.puts output
        end
end

Elixir 中是否有等效的 splat 运算符,例如 *opts? 有没有办法将多个选项而不是选项列表作为参数传递给 exec 函数?

没有 splat 运算符。 Elixir(和 Erlang)中的函数由它们的名称和元数(String.downcase/1Enum.member?/2)定义,可变参数函数会违背这一点。

Erlang 的一位作者 Joe Armstrong 在他的书中提到了这一点 "Programming Erlang: Software for a Concurrent World":

1) a function's arity is part of its name and
2) there are no variadic functions.

如果你想调用带有参数列表的函数(与你想要的相反)可以使用 Kernel.apply/3.

例如

defmodule Test do
  def add(a, b, c) do
    a + b + c 
  end
end

apply(Test, :add, [1, 2, 3])

您不能像 Gazier 所说的那样为 Elixir(或 Erlang 中的函数)指定变量元数。最简单的做法是传递一个列表来代替您想要改变数量的参数,然后使用模式匹配来正确分解它。根据上面的示例,它看起来像这样:

defmodule UnixCommands do
  alias Porcelain.Result
  def run(command,[opts]) do
    optlist = opts |> Enum.reduce(fn o-> "#{o} " end)
    %Result{out: output, status: _} = Porcelain.exec(command, optlist)
  end
end  

注意:我没有测试这段代码,因为我不想安装 Porcelain,但它应该基本上是正确的。