erlang:区分 proplists 和 proplists 列表

erlang: distinguish proplists vs. lists of proplists

我编写了一个函数,它获取 proplistslist proplists anf 键。 如果输入是 proplists 我只是使用 proplists:get_value 来找到对应于键的值。但是如果输入是 proplists 列表,我需要遍历它的所有元素。并在每个人中寻找关键。 我不确定如何区分 listsproplistslists:is_list returns true 他们两个...

proplist 包含元组或原子元素。如果您的案例的列表参数的第一个元素是其中之一,则您有一个 proplist,否则您有一个 proplist 列表。例如,此代码将 return 为给定键找到的值或值列表:

get_value(_Key, []) -> undefined;
get_value(Key, [KV|_]=PL) when is_tuple(KV); is_atom(KV) ->
    proplists:get_value(Key, PL);
get_value(Key, List) when is_list(List) ->
    [get_value(Key, V) || V <- List].

这是一些示例输出:

2> pl:get_value(foo, []).
undefined
3> pl:get_value(foo, [{foo,bar}]).
bar
4> pl:get_value(foo, [[{foo,bar}]]).
[bar]
5> pl:get_value(foo, [[{foo,bar}],[foo],[{foo,baz}]]).
[bar,true,baz]

请注意,在最后一种情况下,第二个参数中的中间 proplist 只有一个键作为原子,没有关联值,因此它在 returned 列表中的值为 true .