RosettaCodeData/Task/Dot-product/CLU/dot-product.clu
2023-07-01 13:44:08 -04:00

30 lines
1.2 KiB
Text

% 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