Time to design a Scheme program for triangulation:
Data Definition:
A matrix is a (listof (listof num)).
Constraints:
1. Each item on a matrix has the same length.
2. The first item on a matrix is by one item longer than the matrix itself.
A trimat is a (listof (listof num)).
Constraints:
1. Each item on a trimat is by one item longer than the following one.
2. The first item on a trimat is by one item longer than the trimat itself.
3. The last one contains two items (nums).
Contract, header, and purpose:
triangulate : matrix -> trimat
(define (triangulate a-matrix) ...)
Purpose: compute a triangular matrix from a-matrix (with the same solution)
Example: see above
Template:
- trivial problem: matrix with one row
- trivial solution: the matrix
- generative step:
subtract the first row from the remaining rows an appropriate number
of times from the remaining ones, eliminate the leading 0
then process the remaining equations
combine the resulting trimat with the first row
Definition:
(define (triangulate mat)
(cond
((empty? (rest mat)) (first mat))
(else (local ((define row1 (first mat)))
(cons row1 (triangulate (subtract-row1-from-all-rows row1 (rest mat))))))))
does every recursive application use triangulate on a matrix?
YES!
Define auxiliary function:
#|
subtract-row1-from-all-rows : (listof num) (listof (listof num)) -> (listof (listof num))
(define (subtract-row1-from-all-rows row1 other-rows) ...)
Purpose: subtract enough multiples of row1 from all rows in other-rows
so that first number of each new one is 0. Eliminate the 0, i.e.,
all rows in result are one shorter than row1
Example:
(subtract-row1-from-all-rows (list 2 3 4)
(list (list 2 3 4)
(list 4 4 4)))
=
(list
(list 0 0)
(list -2 -4))
|#