Skip to content

Instantly share code, notes, and snippets.

@lubien
Last active March 18, 2017 14:23
Show Gist options
  • Save lubien/97fccc66d8ea2187d6e6ae0857fc42ae to your computer and use it in GitHub Desktop.
Save lubien/97fccc66d8ea2187d6e6ae0857fc42ae to your computer and use it in GitHub Desktop.
Multiply two matrices
const
id = x =>
x
, always = x => () =>
x
, not = prop =>
!prop
, composeN = (...fs) => y =>
fs.reduceRight((x, f) => f(x), y)
, c =
composeN
, flip = f => x => y =>
f(y)(x)
, uncurry2 = f => (x, y) =>
f(x)(y)
, map = f => xs =>
xs.map(f)
, reduce = f => xs =>
xs.reduce(f)
, at = n => xs =>
xs[n]
, min = x => y =>
x < y ? x : y
, zipWith = f => xs => ys =>
map(i => f(at(i)(xs))(at(i)(ys)))
(range(0)(min(len(xs))(len(ys))))
, head =
at(0)
, len = xs =>
xs.length
, range = x => y =>
Array.from({length: y - x})
.map((_, i) => i + x)
, cols = M =>
map(flip(col)(M))
(c(range(0), len, head)(M))
, col =
c(map, at)
, rows =
id
, row =
at
, sum = x => y =>
x + y
, mul = x => y =>
x * y
, sumList =
reduce(uncurry2(sum))
, M =
[ [1, 2, 3]
, [4, 5, 6]
]
, N =
[ [ 7, 8]
, [ 9, 10]
, [11, 12]
]
, Maybe = ({
Just: id,
Nothing: always('Nothing')
})
, solve = M => N => {
if (not(c(len, rows)(M) === c(len, cols)(N))) {
return Maybe.Nothing()
}
let
mulPairs =
zipWith(mul)
, mulRowByCols = cols => row =>
map(c(sumList, mulPairs(row)))(cols)
return c(
Maybe.Just,
map(mulRowByCols(cols(N)))
)(rows(M))
}
solve(M)(N)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment