Common Lisp:在列表和数组之间进行转换

时间:2012-03-03 20:24:19

标签: arrays list common-lisp

我们如何在任意嵌套列表和数组之间进行优雅转换?

e.g。

((1 2 3) (4 5 6))

变为

#2A((1 2 3) (4 5 6))

反之亦然

3 个答案:

答案 0 :(得分:19)

列表到2d数组:

(defun list-to-2d-array (list)
  (make-array (list (length list)
                    (length (first list)))
              :initial-contents list))

要列出的2d数组:

(defun 2d-array-to-list (array)
  (loop for i below (array-dimension array 0)
        collect (loop for j below (array-dimension array 1)
                      collect (aref array i j))))

列表到2d的多维表单很容易。

(defun list-dimensions (list depth)
  (loop repeat depth
        collect (length list)
        do (setf list (car list))))

(defun list-to-array (list depth)
  (make-array (list-dimensions list depth)
              :initial-contents list))

要列出的数组更复杂。

也许是这样的:

(defun array-to-list (array)
  (let* ((dimensions (array-dimensions array))
         (depth      (1- (length dimensions)))
         (indices    (make-list (1+ depth) :initial-element 0)))
    (labels ((recurse (n)
               (loop for j below (nth n dimensions)
                     do (setf (nth n indices) j)
                     collect (if (= n depth)
                                 (apply #'aref array indices)
                               (recurse (1+ n))))))
      (recurse 0))))

答案 1 :(得分:8)

列出解决方案的另一个2d数组:

(defun 2d-array-to-list (array)
  (map 'list #'identity array))

并列出到2d数组(但可能没有上次回复的解决方案那么高效):

(defun list-to-2d-array (list)
  (map 'array #'identity list))

答案 2 :(得分:4)

使用强制:将Object强制转换为Output-Type-Spec类型的对象。

(coerce '(1 2 3) 'vector) => #(1 2 3)
(coerce #(1 2 3) 'list)   => '(1 2 3)