使用缺点运算符“|”使用关键字列表

Using the cons operator "|" with Keyword lists

我正在尝试定义一个函数,我在其中指定了关键字列表的一部分,然后将剩余的选项匹配为尾部。

def my_func(foo: 22, bar: 42 | baz) do
  IO.inspect(baz)
end

my_func(foo: 22, bar: 42, another_arg: 11, even_more_args: 12)

并且 baz 的想法是成为包含 [another_arg: 11, even_more_args: 12]

的关键字列表

编译失败,出现以下错误:

misplaced operator |/2

The | operator is typically used between brackets as the cons operator:

[head | tail]

但是,我可以使用以下方法对关键字列表进行模式匹配:

def my_func([{:foo, 22}, {:bar, 42} | baz]) do
end

由于关键字是元组列表的语义糖,我不清楚为什么后一种语法有效,但前者无效。是否缺少某些语法,无法将 | 与关键字一起使用?

发生这种情况是因为关键字列表语法 仅在列表上下文中有效 ,这意味着此类语法无效:

iex> test = foo: 22
** (SyntaxError) iex:8:8: syntax error before: foo

但这是有效的:

iex> test = [foo: 22]
[foo: 22]
def my_func([[foo: 22], [bar: 42] | baz]) do
end

当然前面的语法是不合适的,因为它会形成嵌套列表,但是你不能在没有列表的情况下使用关键字,所以你必须明确地将它写成一个元组。

我建议使用 ++/2 运算符:

def my_func([foo: 22, bar: 42] ++ rest) do
  IO.inspect(rest)
end