Jump to content

Dot product: Difference between revisions

m
→‎JS ES6: Tidied
m (→‎{{header|Haskell}}: Tidied the Maybe version a little)
m (→‎JS ES6: Tidied)
Line 1,593:
 
<syntaxhighlight lang="javascript">(() => {
'"use strict'";
 
// ------------------- DOT PRODUCT -------------------
 
// dotProduct :: [Int] -> [Int] -> Int
const dotProduct = (xs, ys) => {
const sum = xsys => xs ? xs.reduce((a, b)length =>== a + b, 0) : undefined;ys.length
? sum(zipWith(mul)(a, bxs) => a * b, xs, (ys))
) : undefined;
 
 
// ---------------------- TEST -----------------------
 
// main :: IO ()
const main = () =>
return 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.mapreduce((xa, ix) => f(a + x, ys[i])0);
 
return xs.length === ys.length ? (
sum(zipWith((a, b) => a * b, xs, ys))
) : undefined;
}
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) => {
// 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(
return 0, Math.min(xs.length ===, ys.length ? ()
);
 
// MAIN ---
return dotProduct([1, 3, -5], [4, -2, -1]);
return main();
})();</syntaxhighlight>
 
{{Out}}
<syntaxhighlight lang="javascript">3</syntaxhighlight>
 
=={{header|jq}}==
9,655

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.