Computing outer products
The outer product of two arrays can be defined as follows:
def outer_prod op A B =
map (\a -> map (\b -> a `op` b) B) AThis definition is parameterised over the multiplication operator. This allows us to obtain the “standard” outer product:
def std_outer_prod = outer_prod (f64.*)> std_outer_prod [1.0,2.0,3.0] [4.0,5.0,6.0]
[[4.0, 5.0, 6.0],
[8.0, 10.0, 12.0],
[12.0, 15.0, 18.0]]
But we can also use outer_prod to define matrix multiplication:
def dotprod A B =
f64.sum (map2 (*) A B)
def matmul A B =
outer_prod dotprod A (transpose B)> matmul [[1.0,2.0],[3.0,4.0],[5.0,6.0]]
[[7.0,8.0,9.0],[10.0,11.0,12.0]]
[[27.0, 30.0, 33.0],
[61.0, 68.0, 75.0],
[95.0, 106.0, 117.0]]