Compute Dot Product of Two Vectors
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 u开发者_运维技巧se the built-in dotproduct function.
My code so far:
iprod([],[], 0).
iprod([H1|List1], [H2|List2], Result is H1 * H2) :- iprod(List1, List2, Result).
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].
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.
精彩评论