Task

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
   sum the products   (to produce the answer)


Related task

   Vector products


% Compute the dot product of two sequences
% If the sequences are not the same length, it signals length_mismatch
% Any type may be used as long as it supports addition and multiplication
dot_product = proc [T: type] (a, b: sequence[T])
              returns (T) signals (length_mismatch, empty, overflow)
              where T has add: proctype (T,T) returns (T) signals (overflow),
                          mul: proctype (T,T) returns (T) signals (overflow) 
    sT = sequence[T]
    % throw errors if necessary
    if sT$size(a) ~= sT$size(b) then signal length_mismatch end
    if sT$empty(a) then signal empty end
 
    % because we don't know what type T is yet, we can't instantiate it 
    % with a default value, so we use the first pair from the sequences
    s: T := sT$bottom(a) * sT$bottom(b) resignal overflow
    for i: int in int$from_to(2, sT$size(a)) do
        s := s + a[i] * b[i] resignal overflow
    end
    return(s)
end dot_product
 
% calculate the dot product of the given example
start_up = proc ()
    po: stream := stream$primary_output()
 
    a: sequence[int] := sequence[int]$[1, 3, -5]
    b: sequence[int] := sequence[int]$[4, -2, -1]
 
    stream$putl(po, int$unparse(dot_product[int](a,b)))
end start_up