Matrix multiplication: Difference between revisions

→‎JS ES6: Adjusted primitives, tidied.
(→‎JS ES6: Adjusted primitives, tidied.)
Line 3,756:
===ES6===
<lang JavaScript>((() => {
'"use strict'";
 
// matrixMultiply :: Num a => [[a]] -> [[a]] -> [[a]]
Line 3,762:
b => {
const cols = transpose(b);
 
return a.map(
compose(
flip(f => cols.map)(colsf),
dotProduct
)
)(a);
};
 
Line 3,774 ⟶ 3,775:
compose(sum, zipWith(mul)(xs));
 
 
// ----------------------- TEST ------------------------
const main = () =>
JSON.stringify(matrixMultiply(
Line 3,788 ⟶ 3,790:
]));
 
 
// ---------------------- GENERIC ----------------------
 
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
Line 3,797 ⟶ 3,802:
);
 
// flip :: (a -> b -> c) -> b -> a -> c
const flip = f =>
x => y => f(y)(x);
 
// 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 3,826 ⟶ 3,812:
xs.reduce((a, x) => a + x, 0);
 
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => xs.slice(0, n);
 
// transpose :: [[a]] -> [[a]]
Line 3,837 ⟶ 3,817:
// The columns of the input transposed
// into new rows.
// AssumesSimpler input rowsversion of eventranspose, length.assuming input
0 <// rows.length ?of rows[0]even length.map(
Boolean(x, irows.length) =>? rows[0].flatMapmap(
(_, xi) => x[i]rows.flatMap(
x => y v => f(y)(x);v[i]
)
) : [];
 
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
Line 3,849 ⟶ 3,831:
// custom function, rather than with the
// default tuple constructor.
xs => ys => {xs.map(
const(x, i) => f(x)(ys[i])
xs).lengthslice(
lng = Math.min(length(xs), length(ys)),
0, Math.min(xs.length, vs = take(lng)(ys.length);
return take(lng)(xs);
.map((x, i) => f(x)(vs[i]));
};
 
// MAIN ---
9,655

edits