矩阵转置通用Lisp [英] Matrix Transpose Common Lisp
问题描述
好吧,有人告诉我要用通用Lisp制作Matrix Transpose函数。我是一个初学者,所以我不太了解它。
Well, i've been told to make a Matrix Transpose function in common lisp. I'm a beginner, so i don't know so much of it.
我的矩阵是列表列表,我不能使用apply,mapcar或类似于解决它,只是CONS,CAR和CDR。如果没有,我的解决方案将是这样(我放了这个解决方案,以便有人可以使用它):
My Matrix is a list of lists, and i can't use apply, mapcar or similar to solve it, just CONS, CAR and CDR. If not, my solution would be this (I put this solution so someone can use it):
(DEFUN transpose (List)
(apply #'mapcar #'list List)
)
但是我不能使用上述任何内容。
But I can't use anything of the above.
该函数必须是递归的,没有循环或类似内容。
The function has to be recursive, no loops or similar.
所以,问题是,这怎么办?
So, the question is, how could this be done?
这是我走了多远,但它使我产生了溢出错误。我真的不知道该怎么做(我本可以用C ++或Java来做,但是我被要求用Lisp来做...)
This is how far i've gone, but it gets me an overflow error. I don't really know how to do it (i could have done it in C++ or Java, but i'm asked to do it in Lisp...)
(DEFUN transpose (Matrix)
(COND ((NULL Matrix) NIL
)
(T (CONS (CAR(CAR Matrix))(transpose (CONS (CAR(CDR Matrix)) (CDR Matrix))))
)
)
)
感谢任何帮助!
推荐答案
这是一个不使用迭代的简单解决方案或高阶函数。
Here is a simple solution that does not use iteration or high-order functions.
(defun cars (matrix)
"Return a list with all the cars of the lists in matrix"
(if (null matrix)
nil
(cons (car (car matrix)) (cars (cdr matrix)))))
(defun cdrs (matrix)
"Return a list with all the cdrs of the lists in matrix"
(if (null matrix)
nil
(cons (cdr (car matrix)) (cdrs (cdr matrix)))))
(defun transpose (matrix)
"Transpose matrix"
(cond ((null matrix) nil)
((null (car matrix)) nil)
(t (cons (cars matrix) (transpose (cdrs matrix))))))
函数转置
使用两个辅助函数: cars
返回一个列表,其中所有列表的第一元素代表矩阵,而 cdrs
返回一个列表,其中所有其余部分都代表矩阵,因此我们可以使用递归。
The function transpose
uses two auxiliary functions: cars
returns a list with all the first elements of the lists representing the matrix, while cdrs
returns a list with all the remaining parts of the lists representing the matrix, so we can use the recursion.
汽车
通过将 car
递归地应用于列表的所有元素(即列表)来工作,并返回通过 Consing它们而获得的lista。 cdrs
的工作方式相同,这次应用了 cdr
而不是 car
。
cars
works by applying recursively car
to all the elements of the lists (that are lists), and return a lista obtained by "consing" them; cdrs
works in the same way, this time applying cdr
instead of car
.
这篇关于矩阵转置通用Lisp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!