简体   繁体   中英

PROLOG sum of integers inside a list

I have a list of functions

List = [segmentTime(red,a,c,2),segmentTime(green,c,e,3),segmentTime(green,e,h,4),segmentTime(blue,h,i,5)]

How do I find the sum of the integer part of the function of all elements in the list?

ie

sum = 2+3+4+5

A snippet code of a predicate would be extremely useful. Thanks in advance :)

You will be surprised how simple the answer is.

sumList([],0).
sumList([segmentTime(_,_,_,X)|T],Z):- sumList(T,Z1),Z is Z1+X.

?-sumList([segmentTime(red,a,c,2),segmentTime(green,c,e,3),segmentTime(green,e,h,4),segmentTime(blue,h,i,5)],M).
M=14

Hope this helped you.

Another way is to use library(lambda) .

:- use_module(library(lambda)).

getList(L):-
 L = [segmentTime(red,a,c,2),segmentTime(green,c,e,3),segmentTime(green,e,h,4),segmentTime(blue,h,i,5)].

sumOfList(L, S) :-
   foldl(\X^Y^Z^(X = segmentTime(_,_,_,V), Z is Y + V), L, 0, S).

Ouput :

?- getList(L), sumOfList(L, S).
L = [segmentTime(red, a, c, 2), segmentTime(green, c, e, 3), segmentTime(green, e, h, 4), segmentTime(blue, h, i, 5)],
S = 14.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM