This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Coerce bidimensional array into list

3 posts · 1648 views

I know I can use the coerce function to make a list from a given array, However, when I give it a multidimensional array I get a list of all elements.

Is there any "easy way" to get ((1 2) (3 4)) from #((1 2) (3 4))?

Thanks in advance. ;)

Re: Coerce bidimensional array into list

Ferreira wrote:Is there any "easy way" to get ((1 2) (3 4)) from #((1 2) (3 4))?
Actually, #((1 2) (3 4)) is a vector of two elements, both of which are lists, so you can:
[1]> #((1 2)(3 4))
#((1 2) (3 4))
[2]> (coerce #((1 2)(3 4)) 'list)
((1 2) (3 4))
Real two dimensional arrays (with read syntax like #2A((1 2)(3 4)) ) are not sequences, and so as far as I know there is no built in way to transform them into nested list. But it is easy enough with a simple nested loop, like for example:
(defun to-list (2d-array)
  (loop for i from 0 below (array-dimension 2d-array 0)
        collect (loop for j from 0 below (array-dimension 2d-array 1)
                      collect (aref 2d-array i j))))

CL-USER> (to-list #2A((1 2)(3 4)))

((1 2) (3 4))

Re: Coerce bidimensional array into list

Ferreira wrote:I know I can use the coerce function to make a list from a given array, However, when I give it a multidimensional array I get a list of all elements.

Is there any "easy way" to get ((1 2) (3 4)) from #((1 2) (3 4))?

Thanks in advance. ;)
You can use :initial-contents keyword argument for make-array:
(make-array '(2 2) :initial-contents '((1 2) (3 4)))
=>
#2A((1 2) (3 4))