【问题标题】:In erlang how do I unpack a list of tuple in a function argument?在 erlang 中,如何解压缩函数参数中的元组列表?
【发布时间】:2021-05-28 03:36:31
【问题描述】:

我有要求

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

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

我尝试过的:

add_items(AuctionId, ItemList) -> ...

这很好用,但我没有满足要求 - 但是如果我以这种方式定义它,因为它不能与模式匹配,要求会返回一个 function_clause 错误(而且我认为问题不希望我定义以这种方式规范,因为我会写类似的东西

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

这也不符合说尝试用头尾ala []和[H|T]进行递归定义

【问题讨论】:

  • 您应该编辑您的问题,因为阅读它的人不知道您打算做什么。清晰、完整和简洁。
  • @Pascal 我想要做的就是访问参数,我认为函数子句头可能被错误指定,所以我之后想要做什么是无关紧要的..

标签: list function tuples erlang


【解决方案1】:

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

-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() 满足您的要求:

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

  2. 返回值要么是一个包含两个元素元组列表的ok 元组;要么或元组{error,unknown_auction}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 2018-07-04
    • 2021-01-19
    • 2020-12-14
    • 2021-08-30
    • 1970-01-01
    • 2014-08-26
    相关资源
    最近更新 更多