在球拍中转置矩阵(列表列表) [英] Transpose a matrix in racket (list of lists
问题描述
我在球拍中得到了一个清单列表,必须进行转置.
I got a list of lists in racket and have to transpose them.
(: 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))))))))
这是我目前的代码. 我认为问题出在递归调用中(如果我输入错了,请纠正我).
That's my code at the moment. I think the problem is in the recursive call (correct me if I'm wrong please).
实际结果是(list (list 1 4))
.其余的似乎都被忽略了.
The actual outcome is (list (list 1 4))
. The rest seems kinda ignored.
如果有人知道问题或有建议,它将对我有真正的帮助.
It would really help me, if somebody knows the problem, or has a tip.
推荐答案
transpose
的最简单定义是:
(define (transpose xss)
(apply map list xss))
为什么起作用?
(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))
此处List
用大写字母拼写,只是为了表明哪个list
是由用户给出的,而哪个是map
产生的.
Here List
is spelled with capital letters only to show which list
was given by the user and which was produced by map
.
这是一个不太聪明"的解决方案.它使用 矩阵成为转置矩阵的第一行.
Here is a less "clever" solution. It uses that the first column of a matrix becomes the first row in the transposed matrix.
(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))])))
这篇关于在球拍中转置矩阵(列表列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!