-2
$\begingroup$

I want to create a function which allows me to input a list, and then add all of the positive numbers from the list together, leaving any that are negative.

([3,1,-1]) For example only 3 and 1 would be added from this list.

Would I right in thinking the function should be recursive and have a guard?

$\endgroup$
0
$\begingroup$

You don’t need recursion if you use high-order functions and/or List Comprehensions…

sum_positives(List) ->
  lists:sum([X || X <- List, X > 0]).

But you might prefer the recursive version of it…

sum_positives([]) -> 0;
sum_positives([X|Rest]) when X > 0 -> X + sum_positives(Rest);
sum_positives([_|Rest]) -> sum_positives(Rest).
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.