Kronecker product: Difference between revisions
Content added Content deleted
m (fix) |
(→JS ES6: Changed top level of kprod to concatMap - a little cleaner) |
||
Line 220: | Line 220: | ||
const concat = xs => [].concat.apply([], xs); |
const concat = xs => [].concat.apply([], xs); |
||
// |
// concatMap :: (a -> [b]) -> [a] -> [b] |
||
const |
const concatMap = (f, xs) => [].concat.apply([], xs.map(f)); |
||
// 2 or more arguments |
|||
// curry :: Function -> Function |
|||
const curry = (f, ...args) => { |
|||
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] |
||
Line 241: | Line 251: | ||
// kprod :: [[Num]] -> [[Num]] -> [[Num]] |
// kprod :: [[Num]] -> [[Num]] -> [[Num]] |
||
const kprod = (xs, ys) => |
const kprod = (xs, ys) => |
||
concatMap( |
|||
m => map(concat, transpose(m)), |
|||
map(map(f(ys)), xs) |
|||
); |
|||
// (* n) mapped over each element in a matrix |
// (* n) mapped over each element in a matrix |
||
// f :: [[Num]] -> Num -> [[Num]] |
// f :: [[Num]] -> Num -> [[Num]] |
||
const f = curry((mx, n) => |
const f = curry((mx, n) => map(map(x => x * n), mx)); |
||
// TEST ------------------------------------------------------------------- |
// TEST ------------------------------------------------------------------- |
||
return unlines([ |
return unlines(map(rows => unlines(map(show, rows)), [ |
||
kprod([ |
kprod([ |
||
[1, 2], |
[1, 2], |
||
Line 267: | Line 278: | ||
[1, 1, 1, 1] |
[1, 1, 1, 1] |
||
]) |
]) |
||
])); |
|||
].map(rows => unlines(rows.map(show)))); |
|||
})();</lang> |
})();</lang> |
||
{{Out}} |
{{Out}} |