在 erlang 中,如何解压函数参数中的元组列表?

In erlang how do I unpack a list of tuple in a function argument?

我有需求

add_items(AuctionId, [{Item, Desc, Bid}]) -> {ok, [{ItemId, Item]} | {error, unknown_auction}.

如何使用元组列表来编写我的函数体?

我尝试过的:

add_items(AuctionId, ItemList) -> ...

这工作正常,但我没有满足要求 - 但要求 returns 一个 function_clause 错误,如果我这样定义它,因为它不能进行模式匹配(而且我不'认为问题要我以这种方式定义规范,因为我会写类似

的东西
-spec add_items(reference(), [item_info()]) -> 
{ok, [{itemid(), nonempty_string()}]} | {error, unknown_auction()}.

它也不匹配说尝试使用头部和尾部 ala [] 和 [H|T] 进行递归定义

这是您可以执行的操作的示例:

-module(a).
-compile(export_all).

%%add_items(AuctionId, [{Item, Desc, Bid}]) -> 
                     {ok, [{ItemId, Item]} | {error, unknown_auction}.

add_items(AuctionId, Items) ->
    case valid_auction(AuctionId) of
        true -> insert_items(Items, _Results=[]);
        false -> {error, unknown_auction}
    end.

%% Here you should check the db to see if the AuctionId exists:
valid_auction(AuctionId) ->
    ValidAuctionIds = sets:from_list([1, 2, 3]),
    sets:is_element(AuctionId, ValidAuctionIds).

%% Here's a recursive function that pattern matches the tuples in the list:
insert_items([ {Item, Desc, Bid} | Items], Acc) ->
    %%Insert Item in the db here:
    io:format("~w, ~w, ~w~n", [Item, Desc, Bid]),
    ItemId = from_db,
    insert_items(Items, [{ItemId, Item} | Acc]);
insert_items([], Acc) ->
    lists:reverse(Acc).

在shell:

8> c(a).                                
a.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,a}

9> a:add_items(4, [{apple, fruit, 10}]).
{error,unknown_auction}

10> a:add_items(1, [{apple, fruit, 10}, {cards, game, 1}]).
apple, fruit, 10
cards, game, 1
[{from_db,apple},{from_db,cards}]

11> 

shell 交互表明 add_items() 满足您的要求:

  1. 它有两个参数,第二个参数是一个列表,其元素是三元素元组。

  2. return 值是包含两个元素元组列表的 ok 元组;或元组 {error,unknown_auction}.