【发布时间】: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。如果您想更深入地了解这将如何手动工作以及各种树遍历方法,我们都可以跳到更深入的答案。