Scheme中的矩阵添加

时间:2010-03-03 05:58:13

标签: matrix scheme racket

我正在尝试添加矩阵,但它无法正常工作......

(define (matrix-matrix-add a b)
  (map (lambda (row) (row-matrix-add row b))
       a))

(define (row-matrix-add row matrix)
  (if (null? (car matrix))
      '()
      (cons (add-m row (map car matrix))
            (row-matrix-add row (map cdr matrix)))))

(define (add-m row col)
  (if (null? col)
      0
      (+ (car row)
         (car col)
         (add-m (cdr row) (cdr col)))))

2 个答案:

答案 0 :(得分:3)

这是非常短的工作实施。当你可以使用它时,Map很适合去掉一层递归。

(define(matrix-add x y)(map(lambda(x y)(map + x y))x y))

答案 1 :(得分:1)

这是一个有效的实施方案:

(define (matrix-add m1 m2)

  (define (matrix-add-row r1 r2 res-row)
    (if (and (not (null? r1)) (not (null? r2)))
    (matrix-add-row (cdr r1) (cdr r2)
            (cons (+ (car r1) (car r2)) res-row))
    (reverse res-row)))

  (define (matrix-add-each m1 m2 res)
    (if (and (not (null? m1)) (not (null? m2)))
    (let ((res-row (matrix-add-row (car m1) (car m2) ())))
      (matrix-add-each (cdr m1) (cdr m2) (cons res-row res)))
    (reverse res)))
  (matrix-add-each m1 m2 ()))

样本用法和输出:

>  (matrix-add '((7 2) (3 8)) '((4 8) (0 5)))
((11 10) (3 13))
> (matrix-add '((5 2) (4 9) (10 -3)) '((-11 0) (7 1) (-6 -8)))
((-6 2) (11 10) (4 -11))