Coerce bidimensional array into list

Discussion of Common Lisp

Coerce bidimensional array into list

Postby Ferreira » Mon May 04, 2009 11:23 am

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. ;)
Ferreira
 
Posts: 5
Joined: Thu Apr 02, 2009 5:07 am

Re: Coerce bidimensional array into list

Postby Ramarren » Mon May 04, 2009 12:26 pm

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))
Ramarren
 
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland

Re: Coerce bidimensional array into list

Postby dmitry_vk » Mon May 04, 2009 12:58 pm

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))
dmitry_vk
 
Posts: 96
Joined: Sat Jun 28, 2008 8:01 am
Location: Russia, Kazan


Return to Common Lisp

Who is online

Users browsing this forum: Google [Bot] and 1 guest

cron