List 在erlang中,如何解压缩函数参数中的元组列表?
我有这个要求List 在erlang中,如何解压缩函数参数中的元组列表?,list,function,tuples,erlang,List,Function,Tuples,Erlang,我有这个要求 add_items(AuctionId, [{Item, Desc, Bid}]) -> {ok, [{ItemId, Item]} | {error, unknown_auction}. 如何使用元组列表来编写函数体 我所尝试的: add_items(AuctionId, ItemList) -> ... 这很好,但是我没有匹配需求-但是如果我以这种方式定义它,因为它不能与模式匹配,那么需求会返回一个function_子句错误(我认为问题也不希望我以这种方式定义规
add_items(AuctionId, [{Item, Desc, Bid}]) -> {ok, [{ItemId, Item]} | {error, unknown_auction}.
如何使用元组列表来编写函数体
我所尝试的:
add_items(AuctionId, ItemList) -> ...
这很好,但是我没有匹配需求-但是如果我以这种方式定义它,因为它不能与模式匹配,那么需求会返回一个function_子句错误(我认为问题也不希望我以这种方式定义规范,因为我会写类似的东西
-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).
在外壳中:
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()
满足您的需求:
ok
元组;要么是元组{error,unknown\u auction}
你应该编辑你的问题,因为阅读你的问题的人不知道你打算做什么。要清楚、完整和简洁。@Pascal我想做的就是访问参数,我认为function子句头可能指定错误,因此我以后想对它做什么无关紧要。。