Is there any way I can access a specific row from an array, i.e., I have this array:
#2A((1 2) (3 4))
How can I get the first row as #A(1 2)?
Thanks in advance.
#2A((1 2) (3 4))
How can I get the first row as #A(1 2)?
Thanks in advance.
Discuss and learn Lisp programming of all dialects
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.
5 posts · 2685 views
(defun nth-row (array index)
(lambda (col)
(aref array index col)))
And(let* ((array #2A((1 2) (3 4)))
(row-0 (nth-row array 0)))
(dotimes (i 2)
(print (funcall row-0 i))))
And, if you want to be able to change the value(defun nth-row (array index)
(lambda (col &optional new-val)
(if new-val
(setf (aref array index col) new-val)
(aref array index col))))CL-USER> (defparameter *a* (make-array (list 2 2) :initial-contents '((1 2)(3 4))))
*A*
CL-USER> (make-array 2 :displaced-to *a*)
#(1 2)
CL-USER> (make-array 2 :displaced-to *a* :displaced-index-offset 1)
#(2 3)
CL-USER> (make-array 2 :displaced-to *a* :displaced-index-offset 2)
#(3 4)
Note that due to how arrays are laid out in memory this can only be used to access rows or parts of rows, and not columns.Ramarren wrote:See documentation on make-array, in particular :displaced-to and :displaced-index-offset, for example:Hum, my bad, I didn't think about this. Oftenly I use displaced arrays to turn multidimentional arrays into one-dimensional, or to make a destructive version of subseq.Note that due to how arrays are laid out in memory this can only be used to access rows or parts of rows, and not columns.CL-USER> (defparameter *a* (make-array (list 2 2) :initial-contents '((1 2)(3 4)))) *A* CL-USER> (make-array 2 :displaced-to *a*) #(1 2) CL-USER> (make-array 2 :displaced-to *a* :displaced-index-offset 1) #(2 3) CL-USER> (make-array 2 :displaced-to *a* :displaced-index-offset 2) #(3 4)
There is also affine indexing library, which might be used for similar purposes.