Matrix multiplication: Difference between revisions
Content added Content deleted
m (→{{header|REXX}}: added/changed whitespace and comments, changed indentations.) |
|||
Line 1,981: | Line 1,981: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===Iterative=== |
|||
{{works with|SpiderMonkey}} for the <code>print()</code> function |
{{works with|SpiderMonkey}} for the <code>print()</code> function |
||
Line 2,010: | Line 2,012: | ||
<pre>-7,-6,11 |
<pre>-7,-6,11 |
||
-17,-20,25</pre> |
-17,-20,25</pre> |
||
===Functional (ES5)=== |
|||
{{trans|Haskell}} |
|||
<lang JavaScript>(function () { |
|||
'use strict'; |
|||
// matrixMultiply:: [[n]] -> [[n]] -> [[n]] |
|||
function matrixMultiply(a, b) { |
|||
var bt = transpose(b); |
|||
return concatMap(a, function (aRow) { |
|||
return [concatMap(bt, function (bCol) { |
|||
return [sum(zipWith(prod, aRow, bCol))]; |
|||
})] |
|||
}); |
|||
} |
|||
return matrixMultiply( |
|||
[[1, 2], |
|||
[3, 4]], |
|||
[[-3, -8, 3], |
|||
[-2, 1, 4]] |
|||
); |
|||
// --> [[-7, -6, 11], [-17, -20, 25]] |
|||
// GENERIC LIBRARY FUNCTIONS |
|||
// concatMap :: [a] -> (a -> [b]) -> [b] |
|||
function concatMap(xs, f) { |
|||
return [].concat.apply([], xs.map(f)); |
|||
} |
|||
// (a -> b -> c) -> [a] -> [b] -> [c] |
|||
function zipWith(f, xs, ys) { |
|||
return xs.length === ys.length ? ( |
|||
xs.map(function (x, i) { |
|||
return f(x, ys[i]); |
|||
}) |
|||
) : undefined; |
|||
} |
|||
// [[a]] -> [[a]] |
|||
function transpose(lst) { |
|||
return lst[0].map(function (_, iCol) { |
|||
return lst.map(function (row) { |
|||
return row[iCol]; |
|||
}); |
|||
}); |
|||
} |
|||
// sum :: (Num a) => [a] -> a |
|||
function sum(xs) { |
|||
return xs.reduce(function (a, x) { |
|||
return a + x; |
|||
}, 0); |
|||
} |
|||
// product :: n -> n -> n |
|||
function prod(a, b) { |
|||
return a * b; |
|||
} |
|||
})();</lang> |
|||
{{Out}} |
|||
<pre>[[-7, -6, 11], [-17, -20, 25]]</pre> |
|||
=={{header|jq}}== |
=={{header|jq}}== |