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]]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: