Common Lisp: convert between lists and arrays

2019-03-12 17:18发布

问题:

How do we convert elegantly between arbitrarily nested lists and arrays?

e.g.

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

becomes

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

and vice versa

回答1:

List to 2d array:

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

2d array to list:

(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))))

The multi-dimensional form for list to 2d is easy.

(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))

The array to list is more complicated.

Maybe something like this:

(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))))


回答2:

Another 2d array to list solution:

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

And list to 2d array (But maybe not as efficient as the solution of the last reply):

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