【问题标题】:Nested sum in ErlangErlang中的嵌套总和
【发布时间】:2018-04-18 01:30:15
【问题描述】:

我有疑问如何添加列表的数量,包括嵌套列表中的数量,例如:

test:nestedSum([1, [2, 3], [4, 5, 6], 7]).
⇒ 28

到目前为止,我得到了这个:

nestedSum(L) -> nestedSum(L, 0).

nestedSum([H|T], Acc) -> 
nestedSum(T, H + Acc); 

 nestedSum([], Acc) ->
Acc. 

仅适用:

test:nestedSum([1, 2, 3, 4, 5, 6, 7]). 
⇒ 28

但它不会对嵌套总和中的数字求和,我该怎么做?

【问题讨论】:

  • 不值得回答:lists:sum(lists:flatten(L))。查看lists module documentation。如果您想更深入地了解这将如何手动工作以及各种树遍历方法,我们都可以跳到更深入的答案。

标签: list erlang


【解决方案1】:

当列表的头部是列表时,您只需在nestedSum/2 函数中添加一个子句:

% Add this before the two existing clauses.
nestedSum([H|T], Acc) when is_list(H) ->
  nestedSum(T, nestedSum(H) + Acc);

有了这个,你的函数现在可以处理任何嵌套列表:

1> a:nestedSum([1, [2, 3], [4, 5, 6], 7]).
28
2> a:nestedSum([1, [2, 3], [4, 5, 6], 7, [8, [[[9, [[[[[[10]]]]]]]]]]]).
55

【讨论】:

    【解决方案2】:

    你可以使用lists:flatten:

    nestedSum(L) -> nestedSum(lists:flatten(L), 0).
    .
    .
    

    减少列表通常是单行的:

    lists:foldl(fun(X,Sum) -> X + Sum end, 0, lists:flatten([1, [2, 3], [4, 5, 6], 7])).
    

    【讨论】:

    • 真的很有用。扁平化更容易。
    猜你喜欢
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 2013-08-04
    • 2021-06-28
    • 1970-01-01
    • 2022-10-24
    相关资源
    最近更新 更多