Prolog program Write a predicate sumlists(L1, L2, L3) where L1, L2, L3 are lists
ID: 3569544 • Letter: P
Question
Prolog program
Write a predicate sumlists(L1, L2, L3) where L1, L2, L3 are lists of integers. The predicate sumlists succeeds when L3 has a list of integers where each element is the sum of the corresponding elements from L1 and L2. For example sumlists([1,2,3], [3,4,5], L3) should return L3 = [4,6,8]. Handle the case where L1 and L2 are of different lengths (the output list L3 would have the length of the longer input list, and the elements in it after the shorter list ran out would just be equal to the elements in the longer list).
Explanation / Answer
list_sum( [] , [] , [] ) .
list_sum( [] , [Y|Ys] , [Z|Zs] ) :- Z is 0+Y , list_sum( [] , Ys , Zs ) .
list_sum( [X|Xs] , [] , [Z|Zs] ) :- Z is X+0 , list_sum( Xs , [] , Zs ) .
list_sum( [X|Xs] , [Y|Ys] , [Z|Zs] ) :- Z is X+Y , list_sum( Xs , Ys , Zs ) .
The query to execute this is: list_sum([1,2,3],[3,4,5],L3).
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.