gpt4 book ai didi

erlang - Erlang 中的列表累加器

转载 作者:行者123 更新时间:2023-12-02 01:00:22 26 4
gpt4 key购买 nike

这是我在阅读 Joe 的 Erlang 书时找到的代码。但我无法理解。

 odds_and_evens_acc(L) ->
odds_and_evens_acc(L, [], []).
odds_and_evens_acc([H|T], Odds, Evens) ->
case (H rem 2) of
1 -> odds_and_evens_acc(T, [H|Odds], Evens);
0 -> odds_and_evens_acc(T, Odds, [H|Evens])
end;
odds_and_evens_acc([], Odds, Evens) ->
{Odds, Evens}.

请帮我解决这个问题。

最佳答案

%% There are two functions - odds_and_evens_acc/1 and odds_and_evens_acc/3

%% First function. It takes a list of integers and splits it on two lists -
%% odds and evens.
%% The function calls odds_and_evens_acc/3 with three arguments -
%% given List of integers and two empty lists which are
%% accumulators for odds and evens. Actually they are just initial values
%% for lists, where we store odds and evens.
odds_and_evens_acc(L) ->
odds_and_evens_acc(L, [], []).

%% Second function. It takes 3 arguments - list of integers and initial lists for
%% storing odds and evens. The functions works recursively. On each step it
%% takes first element of list, test if it is odd or even, add that elemnt
%% to appropriate list. Then function calls itself
%% with tail (first element deleted) of the list and lists of o/e
%% (one with one new element, another is the same as it was passed).
%% When the list is empty function finishes.
%%
%% Function has two clauses.
%% First clause - the list is not empty - so we should proceed.
%% Function splits it on first element (head)
%% and reminder (tail) with pattern matching ([H|T]).
odds_and_evens_acc([H|T], Odds, Evens) ->
%% Test head if it is odd or even.
%% In both cases the function call itself again with the tail of the list and
%% accumulators (note: head is added in appropriate accumulator).
case (H rem 2) of
1 -> odds_and_evens_acc(T, [H|Odds], Evens);
0 -> odds_and_evens_acc(T, Odds, [H|Evens])
end;

%% Second clause. The list is empty.
%% Function finishes returning tuple with two accumulators
%% which are two lists, the first
%% contains all odd elemnts of the initial list and the second - all evens.
odds_and_evens_acc([], Odds, Evens) ->
{Odds, Evens}.

关于erlang - Erlang 中的列表累加器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22189296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com