## SICP – cap. 2 – Sequenze come interfacce convenzionali – 46 – esercizi

Continuo da qui, copio qui.

Exercise 2.37: Suppose we represent vectors `v = (v_i)` as sequences of numbers, and matrices `m = (m_i j)` 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 as

``````(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 [post precedente]):

``````(define (matrix-*-vector m v)
(map ⟨??⟩ m))

(define (transpose mat)
(accumulate-n ⟨??⟩ ⟨??⟩ mat))

(define (matrix-*-matrix m n)
(let ((cols (transpose n)))
(map ⟨??⟩ m)))``````

Ricopio le procedure `accumulate` e `accumulate-n`

``````(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))

(define (accumulate-n op init seqs)
(if (null? (car seqs))
null
(cons (accumulate op init (map car seqs))
(accumulate-n op init (map cdr seqs)))))``````

Applicando `accumulate-n` ottengo

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

`transpose` è un po’ da pensarci su, vedi Bill (a breve)

``````(define (transpose mat)
(accumulate-n cons null mat))``````

Ancora peggio la moltiplicazione, lo schema dalla Wiki

e –OK, copio Bill– la procedura

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

Raccolgo i codici nel file `m2-37.rkt` ed ecco

Ho utilizzato il codice di Bill the Lizard, migliore –secondo me– ma OK anche sicp-ex e Drewiki.

Annunci
Posta un commento o usa questo indirizzo per il trackback.