sicp-solutions/ex-2.37.scm
Petar Kapriš 2ca5e73a27 Add solutions to exercises from subsection 2.2.3
Notes:
The exercise 2.37 on Hexlet's site has an error, noted in the comments.
Also, their page for exercise 2.38 should probably have 0 tests.

And finally, I did not calculate the exact number in the final exercise
2.43, but I included a relevant discussion.
2025-02-12 16:16:13 +01:00

36 lines
838 B
Scheme

#lang sicp
;;;;
;; Error in the hexlet exercise: the matrix-*-vector line should say
;; m_ij*v_j not m_ij*v_i
;;;;
(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))
'()
(cons (accumulate op init (map car seqs))
(accumulate-n op init (map cdr seqs)))))
(define (dot-product v w)
(accumulate + 0 (map * v w)))
(define (matrix-*-vector m v)
(map (lambda (row)
(dot-product row v))
m))
(define (matrix-*-matrix m n)
(let ((cols (transpose n)))
(map (lambda (row-m)
(map (lambda (col)
(dot-product row-m col))
cols))
m)))
(define (transpose m)
(accumulate-n cons '() m))