How to add elements from sublists with 2 elements (the first element is a string and the second one a number)?

旧城冷巷雨未停 提交于 2020-01-05 06:28:13

问题


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?


回答1:


You just need to break out the string versus the number:

sum_fire( [[_,N]|Tail], Sum ) :-
    sum_fire( Tail, S1 ),
    Sum is N + S1.
sum_fire( [], 0 ).

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 _.




回答2:


Nothing wrong with @mbratch's code (+1), but I would do it tail-recursively (and cut-free) like so:

sum_fire(L, Sum) :- sum_fire(L, 0, Sum).

sum_fire([[_,N]|T], Acc, Sum) :-
    Acc1 is N + Acc,
    sum_fire(T, Acc1, Sum).
sum_fire([], Sum, Sum).



回答3:


SWI-Prolog has library(aggregate) for that:

sum_fire(L, S) :-
  aggregate_all(sum(X), member([_,X], L), S).

Another way to get the task done, using library(apply) and library(lists):

?- maplist(nth1(2), [ [e, 30], [a, 170], [k, 15], [e, 50] ], L), sum_list(L, S).
L = [30, 170, 15, 50],
S = 265.


来源:https://stackoverflow.com/questions/17002163/how-to-add-elements-from-sublists-with-2-elements-the-first-element-is-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!