Talk:Dot product
I suggest replacing the 'for the functional fetishists' JavaScript version
The second JavaScript example, presented (in a light or satirical but perfectly friendly tone) as an example of functional program construction, seems to disqualify itself a bit as an actually plausible or representative exemplar by:
- Disrupting functional composition by using exception handling, rather than returning 'bottom', undefined, or a Maybe monad value when the two lists differ in length, and
- not demonstrating the use of the obvious functional primitives and composition in this case: sum(zipWith(product, xs, ys)
Unless there are objections, I would be inclined to replace it with a slightly more plausible and typical functional definition, built from standard reusable primitives in a way which more visibly corresponds to the definition of a dot product. Using an iterative implementation of zipWith, and assuming ES5 JavaScript (which doesn't perform tail recursion), we could perhaps write something like:
<lang JavaScript>(function () {
'use strict';
function dotProduct(xs, ys) { return xs.length === ys.length ? ( sum(zipWith(product, xs, ys)) ) : undefined; }
// [n] -> n function sum(xs) { return xs.reduce(function (a, x) { return a + x; }, 0); }
// n -> n -> n function product(a, b) { return a * b; }
// (a->b->c) -> [a]->[b]->[c] function zipWith(f, xs, ys) { var nx = xs.length, ny = ys.length, lng = (nx < ny ? nx : ny);
for (var i = 0, lst = []; i < lng; i++) { lst.push(f(xs[i], ys[i])); } return lst; }
return dotProduct([1, 3, -5], [4, -2, -1]);
// -> 3
})();</lang>