Page 1 of 1

Coerce bidimensional array into list

Posted: Mon May 04, 2009 11:23 am
by Ferreira
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

Posted: Mon May 04, 2009 12:26 pm
by ramarren
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:

Code: Select all

[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:

Code: Select all

(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

Posted: Mon May 04, 2009 12:58 pm
by dmitry_vk
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:

Code: Select all

(make-array '(2 2) :initial-contents '((1 2) (3 4)))
=>
#2A((1 2) (3 4))