I'm working on a list that contains sublists with 2 elements each. The first element of each sublist is a string and the second one a number.
[ [e, 30], [a, 170], [k, 15], [e, 50] ]
I want to add all the numbers of each sublist. I tried this one:
sum_fire([H|T],S):-
flatten(H,L),
sum_fire(T,S),
L=[_H1|T1],
sum(T1,S).
but it's completely wrong, I think. How can i get this to work?
SWI-Prolog has library(aggregate) for that:
Another way to get the task done, using library(apply) and library(lists):
Nothing wrong with @mbratch's code (+1), but I would do it tail-recursively (and cut-free) like so:
You just need to break out the string versus the number:
So I'm using
[_,N]
instead of H for the head item because I want what's inside (the number N). I don't care about the string for the sum, so it's_
.