CS Beginner
CS Beginner

Reputation: 43

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?

i.e

sum = 2+3+4+5

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

Upvotes: 0

Views: 94

Answers (2)

joel76
joel76

Reputation: 5605

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.

Upvotes: 0

Ch3steR
Ch3steR

Reputation: 20669

You will be surprised how simple the answer is.

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

OUTPUT

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

Upvotes: 1

Related Questions