方案中的矩阵加法

发布于 2024-08-24 08:51:42 字数 429 浏览 7 评论 0原文

我正在尝试添加一个矩阵,但它不起作用......

(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)))))

I am trying to add a matrix and it is not working...

(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)))))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鱼窥荷 2024-08-31 08:51:42

这是非常简短的工作实现。 Map擅长摆脱一层递归,当你可以使用它时。

(定义(矩阵相加xy)(映射(lambda(xy)(映射+xy))xy))

Here is very short working implementation. Map is good at getting rid of a layer of recursion, when you can use it.

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

逆流 2024-08-31 08:51:42

这是一个有效的实现:

(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))

Here is a working implementation:

(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 ()))

Sample usage and output:

>  (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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文