my attempt to do the exercises in sicp.

Thursday, July 17, 2008

sicp exercise 2.37

;Exercise 2.37.  Suppose we represent vectors v = (vi) as sequences of numbers, and matrices m = (mij) as sequences of vectors (the rows of the matrix). For example, the matrix

;

;is represented as the sequence ((1 2 3 4) (4 5 6 6) (6 7 8 9)). With this representation, we can use sequence operations to concisely express the basic matrix and vector operations. These operations (which are described in any book on matrix algebra) are the following:

;

;We can define the dot product as17

;(define (dot-product v w)
;  (accumulate + 0 (map * v w)))

;Fill in the missing expressions in the following procedures for computing the other matrix operations. (The procedure accumulate-n is defined in exercise 2.36.)

;(define (matrix-*-vector m v)
;  (map <??> m))
;(define (transpose mat)
;  (accumulate-n <??> <??> mat))
;(define (matrix-*-matrix m n)
;  (let ((cols (transpose n)))
;    (map <??> m)))



(define (accumulate op init seq)
  (cond ((null? seq) init)
        (else (op (car seq) (accumulate op init (cdr seq))))))

(define (accumulate-n op init seqs)
  (cond ((null? (car seqs)) (list))
        (else (cons (accumulate op init (map car seqs))
                    (accumulate-n op init (map cdr seqs))))))

(define vector1 (list 2 3 4 5))
(define vector2 (list 5 6 7 8))
(define matrix1 (list (list 1 2 3 4) (list 9 8 7 6) (list 4 3 2 1)))
(define matrix2 (list (list 1 1 1 1) (list 1 1 1 1) (list 1 1 1 1) (list 1 1 1 1)))

(define (dot-product v w)
  (accumulate + 0 (accumulate-n * 1 (list v w))))


(define (matrix-*-vector m v)
  (map (lambda (x)(dot-product x v)) m))


(define (transpose mat)
  (accumulate-n cons (list) mat))


(define (matrix-*-matrix m n)
  (let ((cols (transpose n)))
    (map (lambda(x)(matrix-*-vector cols x)) m)))


(display (dot-product vector1 vector2)) (newline)
(display (matrix-*-vector matrix1 vector1)) (newline)
(display matrix1) (newline)
(display (transpose matrix1)) (newline)
(display (matrix-*-matrix matrix1 matrix2)) (newline)

No comments: