Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Lisp: convert between lists and arrays

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

like image 918
mck Avatar asked Mar 03 '12 20:03

mck


3 Answers

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))))
like image 126
Rainer Joswig Avatar answered Nov 19 '22 09:11

Rainer Joswig


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))
like image 9
kuanyui Avatar answered Nov 19 '22 09:11

kuanyui


Use coerce: Coerce the Object to an object of type Output-Type-Spec.

(coerce '(1 2 3) 'vector) => #(1 2 3)
(coerce #(1 2 3) 'list)   => '(1 2 3)
like image 7
Soul Clinic Avatar answered Nov 19 '22 11:11

Soul Clinic