Kronecker product: Difference between revisions

Content deleted Content added
Add Swift
Hout (talk | contribs)
→‎JS ES6: Updated primitives, layout.
Line 1,766: Line 1,766:
'use strict';
'use strict';


// GENERIC FUNCTIONS ------------------------------------------------------
// ---------KRONECKER PRODUCT OF TWO MATRICES----------

// kprod :: [[Num]] -> [[Num]] -> [[Num]]
const kprod = xs => ys =>
concatMap(
compose(map(concat), transpose))(
map(map(
flip(compose(map, map, mul))(ys)
))(xs)
);

// ------------------------TEST------------------------
// main :: IO ()
const main = () =>
unlines(map(compose(unlines, map(show)))([
kprod([
[1, 2],
[3, 4]
])([
[0, 5],
[6, 7]
]), [], // One empty output line
kprod([
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
])([
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 1, 1, 1]
])
]));


// -----------------GENERIC FUNCTIONS------------------

// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
x => fs.reduceRight((a, f) => f(a), x);


// concat :: [[a]] -> [a]
// concat :: [[a]] -> [a]
Line 1,772: Line 1,810:


// concatMap :: (a -> [b]) -> [a] -> [b]
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) => [].concat.apply([], xs.map(f));
const concatMap = f =>
xs => xs.flatMap(f);


// 2 or more arguments
// flip :: (a -> b -> c) -> b -> a -> c
// curry :: Function -> Function
const flip = f =>
const curry = (f, ...args) => {
x => y => f(y)(x);
const go = xs => xs.length >= f.length ? (f.apply(null, xs)) :
function () {
return go(xs.concat([].slice.apply(arguments)));
};
return go([].slice.call(args, 1));
};


// map :: (a -> b) -> [a] -> [b]
// map :: (a -> b) -> [a] -> [b]
const map = curry((f, xs) => xs.map(f));
const map = f => xs => xs.map(f);

// mul (*) :: Num a => a -> a -> a
const mul = a => b => a * b;


// show :: a -> String
// show :: a -> String
Line 1,797: Line 1,833:
const unlines = xs => xs.join('\n');
const unlines = xs => xs.join('\n');


// MAIN ---

console.log(
// KRONECKER PRODUCT OF TWO MATRICES --------------------------------------
main()

);
// kprod :: [[Num]] -> [[Num]] -> [[Num]]
const kprod = (xs, ys) =>
concatMap(
m => map(concat, transpose(m)),
map(map(f(ys)), xs)
);

// (* n) mapped over each element in a matrix
// f :: [[Num]] -> Num -> [[Num]]
const f = curry((mx, n) => map(map(x => x * n), mx));

// TEST -------------------------------------------------------------------
return unlines(map(rows => unlines(map(show, rows)), [
kprod([
[1, 2],
[3, 4]
], [
[0, 5],
[6, 7]
]), [], // One empty output line
kprod([
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
], [
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 1, 1, 1]
])
]));
})();</lang>
})();</lang>
{{Out}}
{{Out}}