Dot product: Difference between revisions

Content added Content deleted
m (→‎{{header|Haskell}}: Tidied the Maybe version a little)
m (→‎JS ES6: Tidied)
Line 1,593: Line 1,593:


<syntaxhighlight lang="javascript">(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
"use strict";

// ------------------- DOT PRODUCT -------------------


// dotProduct :: [Int] -> [Int] -> Int
// dotProduct :: [Int] -> [Int] -> Int
const dotProduct = (xs, ys) => {
const dotProduct = xs =>
const sum = xs => xs ? xs.reduce((a, b) => a + b, 0) : undefined;
ys => xs.length === ys.length
? sum(zipWith(mul)(xs)(ys))
: undefined;


// ---------------------- TEST -----------------------

// main :: IO ()
const main = () =>
dotProduct([1, 3, -5])([4, -2, -1]);


// --------------------- GENERIC ---------------------

// mul :: Num -> Num -> Num
const mul = x =>
y => x * y;


// sum :: [Num] -> Num
const sum = xs =>
// The numeric sum of all values in xs.
xs.reduce((a, x) => a + x, 0);


return xs.length === ys.length ? (
sum(zipWith((a, b) => a * b, xs, ys))
) : undefined;
}


// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) => {
const zipWith = f =>
// A list constructed by zipping with a
const ny = ys.length;
// custom function, rather than with the
return (xs.length <= ny ? xs : xs.slice(0, ny))
// default tuple constructor.
.map((x, i) => f(x, ys[i]));
xs => ys => xs.map(
}
(x, i) => f(x)(ys[i])
).slice(
0, Math.min(xs.length, ys.length)
);


// MAIN ---
return dotProduct([1, 3, -5], [4, -2, -1]);
return main();
})();</syntaxhighlight>
})();</syntaxhighlight>

{{Out}}
<syntaxhighlight lang="javascript">3</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==