-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.37.rkt
42 lines (34 loc) · 1.01 KB
/
2.37.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#lang sicp
;; 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).
(define (dot-product v w)
(accumulate + 0 (map * v w)))
;; matrix-*-vector
(define (matrix-*-vector m v)
(map (lambda (w) (dot-product v w)) m))
;; transpose
(define (transpose mat)
(accumulate-n cons () mat))
;; m*m
(define (matrix-*-matrix m n)
(let ((cols (transpose n)))
(map (lambda (v) (matrix-*-vector cols v)) m)))
;; accumulate
(define (accumulate-n op init seqs)
(if (null? (car seqs))
nil
(cons (accumulate op init (map car seqs))
(accumulate-n op init (map cdr seqs)))))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op
initial
(cdr sequence)))))
(define (map proc items)
(if (null? items)
nil
(cons (proc (car items))
(map proc (cdr items)))))