Suppose I have the following two equal-sized arrays in my perl program:
my @arr1 = 1..5;
my @arr2 = 6..10;
I’m trying to get their dot-product using the reduce function defined in the List::Util core module but the following is not working for me:
my $dot_prod = reduce { $arr1[$a] * $arr2[$a] + $arr1[$b] * $arr2[$b] }0..$#arr1;
I get 50 as my output instead of the expected 130.
The documentation describes the behavior of
reduceas follows:Thus, in this case, on the first iteration
reducewill set$a = 0and$b = 1, and hence, executeThis temporary result happens to be 20.
Now, for the second iteration,
$ais set to the result of the previous iteratrion and so$a = 20and$b = 2. Thus, the following will be executedwhich is not what we want.
A possible workaround:
prepend an initial
0to the list provided as input toreduceas follows:This gives us the desired result since on the first iteration
$a = $b = 0and we’ll computewhose result will be 6.
Then in the second iteration, we’ll have
$a = 6$b = 1and so we’ll computeetc.