Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help multiplying two lists

Status
Not open for further replies.

RebelsMascot

Programmer
Mar 10, 2005
4
IE
Hey, first off I'm a complete newbie when it comes to Prolog.

My problem is that I'm trying to multiple two lists and sum the values, e.g.

List 1: [1,2,3]
List 2: [4,5,6]
and sum
Sum would be:
Sum = 1*4 + 2*5 + 3*6 = 32

Here's what I have so far:
My problem is the sum part, how do I initialise it to zero?
The checkList predicate is used to check if a list is empty and will return 0 for the ith element

listprod(X, Y, Sum):-
checkList(X, NewListX, Num1),
checkList(Y, NewListY, Num2),

Sum1 is Sum+(Num1*Num2),
listprod(NewListX, NewListY, Sum).

checkList(List, NewList, Int):-
List == [],
Int is 0,
NewList = List.

checkList(List, NewList, Int):-
not List == [],
[Head|Tail] = List,
Int is Head,
NewList = Tail.

Thanks for any help.
 
have you tried writing it this way?
i know it doesnt answer your question but you need to put that "1" there to make it work.

listprod(X, Y, Sum):-
checkList(X, NewListX, Num1),
checkList(Y, NewListY, Num2),

Sum1 is Sum+(Num1*Num2),
listprod(NewListX, NewListY, Sum1).
^
|
 
sorry for that i meant to make that point to the one in the very end but it didnt work out well :D
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top