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.

:mrgreen:

Annunci
Post a comment or leave a trackback: Trackback URL.

Trackbacks

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...

%d blogger hanno fatto clic su Mi Piace per questo: