2
votes

I'm supposed to create a predicate in prolog such that iprod(List1, List2, Result) takes two lists of equal length and each contain integers. The result is the dot product of the two vectors.

For example, List1 = [1,2,3], List2 = [4,5,6], then the result would be 1*4 + 2*5 + 3*6. Also I'm not supposed to use the built-in dotproduct function.

My code so far:

iprod([],[], 0).
iprod([H1|List1], [H2|List2], Result is H1 * H2) :- iprod(List1, List2, Result).
2
So what's the question? Is it "will you do this homework for me"? - Dan Grossman
for guidelines on asking help with homework on SO, read "How to ask and answer homework questions?" - outis
Let me rephrase this. The above is the problem question. I get up to the point where Result = ((0 is 2 * 4) is 1 * 3). Why won't Result be a actual number? Instead its giving me all the calculations? - Victor
You did not show code, so it's hard to imagine what causes the funny expression you've reported for Result. Generally "=" will not evaluate an arithmetic expression, it will just unify as a term that arithmetic expression (formula), but predicate "is" will force the value of an arithmetic expression to be unified. So I suspect you need to understand the different uses of "=" and "is" better. The importance of showing your code in this case is to see whether you appreciate the recursive approach to solving problems in Prolog. After all, the vectors/lists can apparently have any length. - hardmath
Ok, i'll double check to make sure i understand the difference. Here's my code hope it makes sense. iprod([],[], 0). iprod([H1|List1], [H2|List2], Result is H1 * H2) :- iprod(List1, List2, Result). - Victor

2 Answers

4
votes

Using SWI-Prolog:

?- use_module(library(lambda)).

?- maplist(\X^Y^Z^(Z=X*Y),[1,2,3],[4,5,6],Dots).
Dots = [1*4, 2*5, 3*6].

?- maplist(\X^Y^Z^(Z is X*Y),[1,2,3],[4,5,6],Dots).
Dots = [4, 10, 18].
2
votes

In Visual Prolog:

domains
  ilist=integer*

predicates
  iprod(ilist, ilist, integer, integer)

clauses
  iprod([], _, R, R).    
  iprod([X|Xs], [Y|Ys], A, R):-
    M = X * Y,
    Rnew = A + M,
    iprod(XS, Ys, Rnew, R).


goal
  iprod([1,2,3],[4,5,6], 0, R).

Results in 32. Sorry, no other Prolog implementation is available at hand.