Talk:Dot product

From Rosetta Code
Revision as of 16:56, 27 February 2016 by Hout (talk | contribs) (Perhaps a more plausible version of the 'for the functional fetishists' JavaScript example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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 incline 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>