Matrix multiplication: Difference between revisions
→JS ES6: Updated primitives.
(→JS ES6: Updated primitives.) |
|||
Line 2,511:
// matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]]
const matrixMultiply =
const
return
}▼
flip(map)(bt),
dotProduct
▲ };
// dotProduct :: Num a => [[a]] -> [[a]] -> [[a]]
const dotProduct =
compose(sum, zipWith(mul)(xs));
// ----------------------- TEST ------------------------
const main = () =>
[6, -4, 2],
[-3, 5, 0],
[3, 7, -2]
])([
[-1, 1, 4, 8],
[6, 9, 10, 2],
[11, -4, 5, -3]
]));▼
// ---------------------- GENERIC ----------------------
//
const
//
const
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// map :: (a -> b) -> [a] -> [b]
const map = f =>
// The list obtained by applying f
// to each element of xs.
// (The image of xs under f).
xs => xs.map(f);
// mul :: Num a => a -> a -> a
const mul = a =>
b => a * b;
// sum :: (Num a) => [a] -> a
Line 2,536 ⟶ 2,577:
xs.reduce((a, x) => a + x, 0);
//
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => xs.slice(0, n);
// transpose :: [[a]] -> [[a]]
const transpose = rows =>
// The columns of the input transposed
// into new rows.
// Assumes input rows of even length.
0 < rows.length ? rows[0].map(
(x, i) => rows.flatMap(
x => x[i]
)
) : [];
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
▲ // TEST
const zipWith = f =>
▲ return matrixMultiply(
// A list constructed by zipping with a
▲ [
// custom function, rather
// default tuple
xs => ys =>
lng = Math.min(length(xs), length(ys)),
▲ ],
vs = take(lng)(ys);
▲ [11, -4, 5, -3]
▲ ]
▲ );
//
return main();
▲ // [33, 42, 38, -14], [17, 74, 72, 44]]
}))();</lang>
{{Out}}
<
=={{header|jq}}==
|