在球拍中转置矩阵(列表列表

b4s*_*you 5 scheme transpose list matrix racket

我有一个球拍列表清单,必须转置它们.

(: transpose ((list-of(list-of %a)) -> (list-of (list-of %a))))

(check-expect (transpose (list (list 1 2 3)
                               (list 4 5 6)))
              (list (list 1 4)
                    (list 2 5)
                    (list 3 6)))

(define transpose
  (lambda (xs)
    (cond
      ((empty? xs)empty)
      ((pair? xs)(make-pair  (make-pair (first(first xs))  (make-pair (first(first(rest xs)))empty)) (transpose (rest(rest xs))))))))
Run Code Online (Sandbox Code Playgroud)

那是我目前的代码.我认为问题在于递归调用(如果我错了请纠正我).

实际结果是(list (list 1 4)).其余的似乎有点被忽视了.

如果有人知道这个问题,或者有小费,这对我有帮助.

soe*_*ard 15

最简单的定义transpose是:

(define (transpose xss)
  (apply map list xss))
Run Code Online (Sandbox Code Playgroud)

它为什么有效?

  (apply map list '((a b) (d e))
= (apply map List '((a b) (d e))    ; use List rather than list
= (map List '(a b) '(d e))
= (list (List 'a 'd) (List 'b e))
= '((a d) (b e))
Run Code Online (Sandbox Code Playgroud)

这里List拼写大写字母只显示list由用户给出的和由谁产生的map.

这是一个不那么"聪明"的解决方案.它使用矩阵的第一列成为转置矩阵中的第一行.

(define transpose
  (lambda (xss)
    (cond
      [(empty? xss)         empty]
      [(empty? (first xss)) empty]
      [else                 (define first-column   (map first xss))
                            (define other-columns  (map rest  xss))
                            (cons first-column
                                  (transpose other-columns))])))
Run Code Online (Sandbox Code Playgroud)

  • Python中的等价物是`apply(zip,[['a','b'],['c','d'],['e','f']])`.我知道你没有问过Python,但我提供的是一般知识.Python有很多以"垃圾场 - 战争"风格结合在一起的lispy位.与任何真正的口齿不清相比,与朋友分享也更容易. (2认同)