Search code examples
lambdaprolog

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 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).

Solution

  • 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.