List Accumulators

Suppose we want to separate  a container type object into its component parts. Accumulators provide an elegant solution to this problem. We create a list of accumulators and traverse through the original list and collect each element into the appropriate component. In Ruby, we can use inject method to implement accumulators. Suppose we want to split a list of integers into two lists of even and odd numbers. We create two empty accumulator lists for even and odd numbers.


(5..30).inject([[], []]) do |evenOdds, n|
evenOdds[n%2].push(n)
evenOdds
end

=> [[6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30], [5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]]

Accumulators fit naturally into functional programming language. Here is an Erlang code to do the same.


module(acc).
-export([even_odds/1]).
-import(lists, [reverse/1]).
even_odds(List) ->
even_odds(List, [], []).
even_odds([H|T], Evens, Odds) ->
case (H rem 2) of
0 -> even_odds(T, [H|Evens], Odds);
1 -> even_odds(T, Evens, [H|Odds])
end;
even_odds([],Evens, Odds) ->
[lists:reverse(Evens), lists:reverse(Odds)].


acc:even_odds(lists:seq(5, 30)).

[[6,8,10,12,14,16,18,20,22,24,26,28,30],
[5,7,9,11,13,15,17,19,21,23,25,27,29]]

Blog at WordPress.com.