reverb1010
reverb1010

Reputation: 41

Erlang: parsing and summing a list

I have been working on how solve an Erlang program that is to perform distributed address spacing. I am trying to create a method that takes an associative and commutative operator, as well a list of values, and then returns the answer by applying the operator to the values in the list.

The following two examples represent what the input/output are supposed to look like.

Example 1

Input: sum(fun(A,B) -> A+B end, [2,6,7,10,12]

Output: 37

Example 2

Input: sum(fun (A,B) -> A++B end , ["C", "D", "E"]).

Output: "CDE"

This is the code I have so far, which is just a function that adds the elements in a list. How would I change the method to fit the above examples, as well as to produce the correct result? Right now, the code just returns the sum.

-module(sum).
-export([sum/1]).

sum(L) -> 
   sum(L, 0).

sum([H|T], Acc) -> 
   sum(T, H + Acc); 

sum([], Acc) ->
   Acc.

I wanted to try this serially, before attempting a parallelized version. Please know that before posting this, I tried to look for similar coding examples elsewhere that would help answer my question, but I could not find much, which is why I am posting this.

Upvotes: 1

Views: 1353

Answers (1)

7stud
7stud

Reputation: 48649

How about this:

-module(my).
-compile(export_all).

sum(Func, Data, Acc) ->
    lists:foldr(Func, Acc, Data).

In the shell:

13> c(my).                                              
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}

14> my:sum(fun(X, Acc) -> X+Acc end, [2,6,7,10,12], 0). 
37

15> my:sum(fun(X, Acc) -> X++Acc end, ["C", "D", "E"], []). 
"CDE"

The starting value for the Accumulator(Acc) needs to be different depending on the operator.

Upvotes: 2

Related Questions