I started to study Scheme and I do not understand some of it. I'm using DrRacket.
I wrote the following code:
(define mult_mat
(λ (A B)
(Trans_Mat (map (λ (x) (mul_Mat_vec A x))
(Trans_Mat B)))))
That uses this functions:
(define Trans_Mat
(λ (A)
(apply map (cons list A))))
(define mul_Mat_vec
(λ (A v)
(map (λ (x) (apply + (map * x v)))
A)))
In mult_mat
, I multiply the matrix A in each vector of the transpose matrix B.
It works fine.
I found a code on the web that makes the multiplication in a way that I don't understand:
(define (matrix-multiply matrix1 matrix2)
(map
(λ (row)
(apply map
(λ column
(apply + (map * row column)))
matrix2))
matrix1))
In this code, row
is a list of the lists of matrix A, but I don't understand how the column
updates.
This part of the code: (apply + (map * row column))
is the dot product of vector row
and vector column
For example: A is a matrix 2X3 and B is a matrix 3X2 and if instead of (apply + (map * row column))
I write 1
, then I'll get a matrix 2X2 with entries valued 1
I don't understand how it works.
Thanks.
Ah, the old
( apply map foo _a_list_ )
trick. Very clever.In fact
(apply map (cons list A))
is the same as(apply map list A)
. That's just howapply
is defined to work.Trying out some concrete examples usually helps to "get it":
Matrix transposition. (list of lists, really.)
So you have
Notice it's
(λ B_column ...
, without parentheses. In((λ args ...) x y z)
, when the lambda is entered,args
gets all the arguments packaged in a list:Also notice
follows the same "tricky" pattern. It's in fact the same as
by the definition of
map
.Thus, by applying the
map
, the matrix is "opened up" into the list of its rows, and then whenmap
gets to work on these rows as its arguments, the lambda function gets applied to each row's subsequent numbers, in unison, correspondingly; thus achieving the same effect as the explicit transposition had. But now the added bonus is, we don't need to transpose the result back into the proper form, as we have to do with your first version.This is very clever, and nice.