; matrix mutliplication program in LISP ; == read n numbers ; return a list of the numbers read in order: (v1 v2 ...) (defun read-row (n) (cond ((> n 0) (cons (read) (read-row (- n 1)))) ) ) ; == read nr rows each of nc values ; return the list: (row1 row2 ...) i.e ((v1,1 v1,2...)(v2,1 ...)...) (defun read-rows (nr nc) (cond ((> nr 0) (print "row: ") (cons (read-vec nc) (read-rows (- nr 1) nc))) (t ()) ) ) ; read the dimensions (nr nc) fo a matrix and then nr rows ; return (nr nc ((v1,1 v1,2 ...)(v2,1 v2,2 ...) ... )) (defun read-mat () (print "n_rows? n_cols? ") (setq nr (read)) (setq nc (read)) (cons nr (cons nc (read-rows nr nc))) ) ; given two vectors v1 = (a1 a2 ... an), v2 = (b1 b2 ... bn) ; return their product: a1*b1 + a2*b2 + ... + an*bn (defun dot-prod (v1 v2) (cond ((null v1) nil) ((and (null (cdr v1))(null (cdr v2))) (* (car v1)(car v2))) ((neq (length v1)(length v2)) nil) (t (+ (* (car v1)(car v2)) (dot-prod (cdr v1)(cdr v2)))) ) ) ; == given list = (a1 a2 ... ) ; return an or nil if list is too short (defun nth (n list) (cond ((null list) nil) ((= n 1) (car list)) (t (nth (- n 1) (cdr list))))) ; == given the rows of a matrix ((v1,1 v1,2 ...)(v2,11 ...) ...) ; return column n : (v1,n v2,n ... vm,n) (defun column (n mat-rows) (cond ((null mat-rows) nil) (t (cons (nth n (car mat-rows)) (column n (cdr mat-rows)))))) ; == given a vec (one row of the 1st matrix) ; a row number (start w/1) ; a second matrix ; return a row of products: (vec*col1 vec*col2 ... ) (defun make-prod-row (n vec mat) (cond ((not (> n (length (car mat)))) ; (print (list "dot-prod" vec (column n mat))) ; (terpri) (cons (dot-prod vec (column n mat)) (make-prod-row (+ 1 n) vec mat))) (t nil))) ; == given two mats in the form ((v1,1 v1,2 ...)(v2,1 v2,2 ...) ...) ; return the mat of their product (defun mat-mult (mata matb) (cond ((null mata) nil) (t (cons (make-prod-row 1 (car mata) matb) (mat-mult (cdr mata) matb) ) ) ) ) ;; == main function ;; reads two matrices and mutiplies them if possible (defun mult () (prog (a b) (print " enter A") (terpri) (setq a (read-mat)) (print a) (terpri) (print " enter B") (terpri) (setq b (read-mat)) (print b)(terpri) (cond ((= (cadr a) (car b)) (print (mat-mult (cddr a) (cddr b)))) (t (print "can't multiply")) ) ) t )