;;; $Id: matrix-ops.scm,v 1.3 2006/01/05 22:24:09 leavens Exp $ ;;; Some simple matrix operations that demonstrate the use of "map" ;;; and "all". These wouldn't be efficient, since we aren't using vectors. ;;; See matrix-ops.tst for some examples. (module matrix-ops (lib "typedscm.ss" "typedscm") (provide scalar-multiply scalar-add transpose parse-matrix) (deftype scalar-multiply (-> (number matrix) matrix)) (deftype scalar-add (-> (number matrix) matrix)) (deftype transpose (-> (matrix) matrix)) (deftype parse-matrix (-> ((list-of (list-of number))) matrix)) (require (lib "all-mod.scm" "lib342")) ;; a matrix is represented as a list of list of numbers, e.g. ;; ((3 4 5) ;; (1 3 2) ;; (1 3 4) ;; (7 9 12)) (defrep (matrix (list-of (list-of number)))) (define scalar-multiply (lambda (scalar mat) ;; ENSURES: result is mat with each element multiplied by scalar (map (lambda (row) (map (lambda (elem) (* scalar elem)) row)) mat))) (define scalar-add (lambda (scalar mat) ;; ENSURES: result is mat with each element summed with scalar (map (lambda (row) (map (lambda (elem) (+ scalar elem)) row)) mat))) (define transpose ;; ENSURES: result is the transpose of mat (lambda (rows) ;; (displayln "rows is " rows) (if (all null? rows) '() (cons (map car rows) (transpose (map cdr rows)))))) (define parse-matrix (lambda (rows) (cond ((not ((list-of (list-of number?)) rows)) (error "parse-matrix: argument should be a list of lists of numbers" rows)) ((not (or (null? rows) (null? (car rows)) (all (lambda (r-len) (= (length (car rows)) r-len)) (map length (cdr rows))))) (error "parse-matrix: rows are now of equal length" rows)) (else rows)))) ) ; end module