Common Lisp的:列表和数组之间的转换 [英] Common Lisp: convert between lists and arrays

查看:526
本文介绍了Common Lisp的:列表和数组之间的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何优雅地转换任意嵌套列表和阵列之间?

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

例如

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

变为

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

和反之亦然

推荐答案

列表二维数组:

(defun list-to-2d-array (list)
  (make-array (list (length list)
                    (length (first list)))
              :initial-contents 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))))

有关列表2D多维的形式很容易。

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.

也许是这样的:

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

这篇关于Common Lisp的:列表和数组之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆