I am trying to make a function that does matrix-vector multiplication in scheme. I am confused by the results. Here is my code that defines a function that computes the dot products of two vectors:
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (dot-product v w)
(accumulate + 0 (map * v w)))
This returns the expected dot product of vectors, like (list 2 3 4)
and (list 1 1 1)
. But when I try to compute the product of a matrix and vector with
(define (matrix-*-vector m v)
(map (lambda (x) dot-product v x) m))
this function will simply return the original matrix m
, rather than the expected result. I'm extra confused because I can write this in Wolfram Language just fine and it behaves as expected:
myMatrixMult[m_,v_]:=Map[Function[x,Dot[v, x]], m]
(I don't think you need to be expert in either language to see the similarities).
What am I misapprehending about the scheme implementation? What needs to be done in order to define matrix-vector multiplication using map
and dot-product
?
You are missing parens in your lambda
:
(lambda (x) dot-product v x)
never calls dot-product
, it just returns x
.
You need
(lambda (x) (dot-product v x))