Erlang中的嵌套总和

时间:2017-11-05 23:01:00

标签: list erlang

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

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

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

2 个答案:

答案 0 :(得分:6)

当列表的头部是列表时,您只需要为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

答案 1 :(得分:5)

您可以使用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])).