Elixir-如何使用不在最后位置的默认函数参数?

Sla*_*lag 1 elixir

考虑以下简单功能:

def myfun(first \\ :a, middle \\ :b, last \\ :c) do
  {first, middle, last}
end
Run Code Online (Sandbox Code Playgroud)

我想为第一个和最后一个参数传递该函数的特定值,并让它推断出中间参数。我期望这样的事情可能会起作用:

{:foo, :b, :baz} = myfun(:foo, _, :baz)
Run Code Online (Sandbox Code Playgroud)

但事实并非如此。

什么是完成我要完成的正确方法?

Paw*_*rok 5

正如Aleksei Matiushkin在评论中提到的那样,Keyword当所有参数都是可选的时,使用可能是更好的选择。它看起来像这样:

defmodule Fun do
  def myfun(options \\ []) do
    first = Keyword.get(options, :first, :a)
    second = Keyword.get(options, :second, :b)
    third = Keyword.get(options, :third, :c)

    {first, second, third}
  end
end

Fun.myfun(first: 1, third: 3) # => {1, :b, 3}
Fun.myfun(second: 2) # => {:a, 2, :c}
Fun.myfun() # => {:a, :b, :c}
Run Code Online (Sandbox Code Playgroud)