Talk:Dot product

Revision as of 19:38, 27 February 2016 by Rdm (talk | contribs) (Make voices distinguishable)

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:

  1. 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
  2. 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> -- --Hout (talk) 16:56, 27 February 2016 (UTC)

I'd be inclined to say go for it.
That said, I'd also be inclined to replace zipWith with something like:
<lang javascript> function zipWith(f, xs, ys) {
       return xs.length === ys.length ? (
           xs.map(function(x, i) {return f(x,ys[i])})
       ) : undefined;
   }</lang>
Or, if you feel like zipWith should work with mis-matched argument lengths, give this implementation some other name. ... There is some use for the mismatched approach, but most of the time - including this example - that's just an error.
(I am not really fond of javascript's implementation of .map(), but this kind of thing is what it was designed for.)
And, thanks! --Rdm (talk) 19:36, 27 February 2016 (UTC)
Return to "Dot product" page.