Matrix Transpose Common Lisp

Sli*_*gon 1 recursion transpose common-lisp

好吧,我被告知要在普通的lisp中制作一个Matrix Transpose功能.我是初学者,所以我不太了解它.

我的矩阵是一个列表列表,我不能使用apply,mapcar或类似的解决它,只有CONS,CAR和CDR.如果没有,我的解决方案将是这个(我把这个解决方案,所以有人可以使用它):

(DEFUN transpose (List)
    (apply #'mapcar #'list List)
)
Run Code Online (Sandbox Code Playgroud)

但我不能使用上述任何东西.

该函数必须是递归的,没有循环或类似的.

所以,问题是,怎么办呢?

这是我走了多远,但它让我出现溢出错误.我真的不知道该怎么做(我本可以用C++或Java完成它,但我被要求在Lisp中做到这一点......)

    (DEFUN transpose (Matrix)
        (COND   ((NULL Matrix) NIL
                ) 
                (T (CONS (CAR(CAR Matrix))(transpose (CONS (CAR(CDR Matrix)) (CDR Matrix))))
                )
        )
    )
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

Ren*_*nzo 5

这是一个不使用迭代或高阶函数的简单解决方案.

(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))))))
Run Code Online (Sandbox Code Playgroud)

该函数transpose使用两个辅助函数:cars返回一个列表,其中包含表示矩阵的列表的所有第一个元素,同时cdrs返回一个列表,其中列表的所有剩余部分代表矩阵,因此我们可以使用递归.

cars通过递归地car应用于列表的所有元素(即列表),并返回通过"消耗"它们获得的列表来工作; cdrs以同样的方式工作,这次应用cdr而不是car.