; http://cap-lore.com/MathPhys/Field/inv.html
(lambda (rfi zero zer? one fa fn fm fi) (letrec (
(fs (lambda (a b) (fa a (fn b))))
; (ex (lambda (m v)(write (list m v))(newline) v))
(tr (fileVal "transpose"))
(sm (lambda (s a)(map (lambda (w) (fm s w)) a)))
(fms (lambda (a s b) (if (null? a) (sm (fn s) b) (if (null? b) a
(cons (fs (car a) (fm s (car b))) (fms (cdr a) s (cdr b)))))))
(deter (lambda (x) (if (null? x) one
(if (zer? (caar x)) ; look for a row which does not begin with zer
(let lz ((v (cdr x))) (if (null? v) zero (if (zer? (caar v)) (lz (cdr v))
(deter (cons (map fa (car x) (car v)) (cdr x))))))
(fm (caar x) (let ((top (cdar x))(iv (fi (caar x))))
(deter (map (lambda (q)(fms (cdr q) (fm iv (car q)) top)) (cdr x)))))))))
(inv (lambda (a np) (let ol ((ut (let inx (
(a (let pad ((x a)(e (list one)))
(if (null? x) '() (cons (let ap ((z (car x))(ln a))
(if (null? ln) e (if (null? z) (cons zero (ap z (cdr ln)))
(cons (car z)(ap (cdr z)(cdr ln))))))
(pad (cdr x) (cons zero e))))))
(np np))
(if (null? a) '() (let* (
(A (let tf ((a a)) (if (null? a) (np (list one))
(if (zer? (caar a)) (let ((z (tf (cdr a))))
(cons (car z) (cons (car a) (cdr z)))) a))))
(i (fi (caar A)))
(b (map (lambda (z) (fm i z)) (cdar A))))
(cons b (inx (map (lambda (x w) (fms x w b))
(map cdr (cdr A)) (map car (cdr A)))
(lambda (w) (np (cons (fn (ip w b)) w))))))))))
(if (null? ut) '() (cons
(let eg ((top (car ut))(bod (cdr ut))) (if (null? bod) top
(eg (fms (cdr top) (car top) (car bod))(cdr bod))))
(ol (cdr ut)))))))
(ip (lambda (x y)(if (or (null? x) (null? y)) zero (fa (fm (car x)(car y))
(ip (cdr x)(cdr y))))))
(mp (lambda (a b)(if (null? a) a (let ((b (tr b)))
(map (lambda(x) (map (lambda (y) (ip x y)) b)) a)))))
(e= (lambda (a b) (zer? (fs a b))))
(v= (lambda (a b) (or (and (null? a) (null? a))
(and (pair? a) (pair? b) (e= (car a)(car b)) (v= (cdr a)(cdr b))))))
(m= (lambda (a b) (or (and (null? a) (null? a))
(and (pair? a) (pair? b) (v= (car a)(car b)) (m= (cdr a)(cdr b))))))
(it? (let ((trz (lambda (l) ; identity matrix test (once was tmz)
(let rz ((w l)) (or (null? w) (and (zer? (car w)) (rz (cdr w))))))))
(lambda (m) (or (null? m) (let ((c (map car m))(R (map cdr m)))
(and (e= one (car c))
(trz (car R))
(trz (cdr c))
(it? (cdr R))))))))
(rm (let ((DoL ((fileVal "Do") 'DoL)))
(lambda (n) (DoL n (lambda (h) (DoL n (lambda (j) (rfi)))))))))
(list rm mp inv ip tr deter it? v= m=)))