2012-03-03 49 views

回答

18

列表以二維數組:

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

謝謝你 - 任何想法的xd數組/列表? – mck 2012-03-03 20:54:57

+0

@mck:指定您想要的級別,並將正確的維度列表提供給MAKE-ARRAY。 – 2012-03-03 21:08:54

+0

那需要爲3d數組寫一個單獨的函數? – mck 2012-03-03 21:54:51

7

另一個二維數組列出的解決方案:

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

和列表,以二維數組(但也許不是一樣有效,最後回覆的解決方案):

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