/*
Dot product (Rosetta code) in Picat.
http://rosettacode.org/wiki/Dot_product
"""
Create a function/use an in-built function, to compute the dot product,
also known as the scalar product of two vectors. If possible, make the
vectors of arbitrary length.
As an example, compute the dot product of the vectors
[1, 3, -5] and [4, -2, -1].
If implementing the dot product of two vectors directly, each vector must
be the same length; multiply corresponding terms from each vector then
sum the results to produce the answer.
"""
This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com
See also my Picat page: http://www.hakank.org/picat/
*/
% import util.
% import cp.
main => go.
go =>
L1 = [1, 3, -5],
L2 = [4, -2, -1],
% dot_product/2
println(dot_product=dot_product(L1,L2)),
catch(println(dot_product([1,2,3,4],[1,2,3])),E, println(E)),
% dot_product2/2
println(dot_product2=dot_product2(L1,L2)),
catch(println(dot_product2=dot_product2([1,2,3,4],[1,2,3])),E, println(E)),
nl.
dot_product(L1,L2) = _, L1.length != L2.length =>
throw($dot_product_not_same_length(L1,L2)).
% using list comprehension
dot_product(L1,L2) = sum([L1[I]*L2[I] : I in 1..L1.length]).
dot_product2(L1,L2) = _, L1.length != L2.length =>
throw($dot_product2_not_same_length(L1,L2)).
% using zip
dot_product2(L1,L2) = sum([LL1*LL2 : {LL1,LL2} in zip(L1,L2)]).