mck*_*mck 15 arrays list common-lisp
我们如何在任意嵌套列表和数组之间进行优雅转换?
例如
((1 2 3) (4 5 6))
Run Code Online (Sandbox Code Playgroud)
变
#2A((1 2 3) (4 5 6))
Run Code Online (Sandbox Code Playgroud)
反之亦然
Rai*_*wig 21
列表到2d数组:
(defun list-to-2d-array (list)
(make-array (list (length list)
(length (first list)))
:initial-contents list))
Run Code Online (Sandbox Code Playgroud)
要列出的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))))
Run Code Online (Sandbox Code Playgroud)
列表到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))
Run Code Online (Sandbox Code Playgroud)
要列出的数组更复杂.
也许是这样的:
(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))))
Run Code Online (Sandbox Code Playgroud)
列出解决方案的另一个2d数组:
(defun 2d-array-to-list (array)
(map 'list #'identity array))
Run Code Online (Sandbox Code Playgroud)
并列出到2d数组(但可能没有上次回复的解决方案效率):
(defun list-to-2d-array (list)
(map 'array #'identity list))
Run Code Online (Sandbox Code Playgroud)
使用强制:将对象强制为类型为 Output-Type-Spec 的对象。
(coerce '(1 2 3) 'vector) => #(1 2 3)
(coerce #(1 2 3) 'list) => '(1 2 3)
Run Code Online (Sandbox Code Playgroud)