ap1711
ap1711

Reputation: 11

How do we add each element of two lists in sequence in Prolog?

Write a Prolog predicate seqadd/3 such that seqadd(X,Y,Z) succeeds when X and Y are lists of integers of the same length and Z is their sequence sum.

Upvotes: 1

Views: 318

Answers (1)

Ch3steR
Ch3steR

Reputation: 20669

You want to add 1st element of 1st list to 1st element of 2nd list and so on. Right? If yes then you can use this approach below.

seqsum([],[],[]).
seqsum([H|T],[H1|T1],[H2|Z]):- H2 is H+H1 , seqsum(T,T1,Z).

OUTPUT

?- seqsum([1,2,3],[4,5,6],Z).
   Z = [5,7,9]
   yes

Hope this helped you.

Upvotes: 2

Related Questions