Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Lisp: how to access a row of a certain multi-dimension array?

Tags:

common-lisp

Let's say I wrote

(setf s (make-array (list 9 9) :element-type 'bit))

so s is a 9x9 matrix of bits.

and I want to get the 1st row of s. How do I get that?

I could have done the following:

(setf s (make-array 9 
          :element-type 'array 
          :initial-element 
          (make-array 9 :element-type 'bit)))

and access the first row by (svref s 0).
But I want to know if there is a built-in way.
(And the 2 dim array seems to allocate less bytes).

like image 409
h__ Avatar asked Sep 08 '12 01:09

h__


1 Answers

(defun array-slice (arr row)
    (make-array (array-dimension arr 1) 
      :displaced-to arr 
       :displaced-index-offset (* row (array-dimension arr 1))))

This only works for row slices and doesn't, IIRC, copy the array. Writing to the slice will modify the original array.

like image 135
krzysz00 Avatar answered Oct 15 '22 01:10

krzysz00