Common lisp how to set element to 2d array?

I think I'm just using setq (or setf , I'm not quite sure of the difference), but I don't understand how to reference the [i][j] th element in an array in lisp.

My launch condition:

 ? (setq x (make-array '(3 3))) #2A((0 0 0) (0 0 0) (0 0 0)) 

I want to change, say, the 2nd element of the third β€œline” to do this:

 ? ;;; What Lisp code goes here?! #2A((0 0 0) (0 0 0) (0 "blue" 0)) 

The following, which I would think of, gives an error:

 (setq (nth 1 (nth 2 x)) "blue") 

So what is the correct syntax?

Thanks!

+4
source share
3 answers

I think the correct way is to use setf with aref as follows:

 (setf (aref x 2 1) "blue") 

See the link for more details.

+13
source

You can find the ARRAY operation dictionary in Common Lisp HyperSpec (the web version of the ANSI Common Lisp standard:

http://www.lispworks.com/documentation/lw50/CLHS/Body/c_arrays.htm

AREF and (SETF AREF) described here:

http://www.lispworks.com/documentation/lw50/CLHS/Body/f_aref.htm

The syntax for setting an array element is: (setf (aref array &rest subscripts) new-element) .

Basically, if you want to install something in Common Lisp, you just need to know how to get it:

 (aref my-array 4 5 2) ; access the contents of an array at 4,5,2. 

Then the installation operation is schematically:

 (setf <accessor code> new-content) 

It means:

 (setf (aref my-array 4 5 2) 'foobar) ; set the content of the array at 4,5,2 to ; the symbol FOOBAR 
+7
source

Right call

 (setf (aref x 2 1) "blue") 

setq used when you assign a variable. Only setf knows how to "enter" into composite objects, as with setting a value in your array. Of course, setf also knows how to assign variables, so if you stick with setf , you'll always be fine.

+3
source

Source: https://habr.com/ru/post/1495342/


All Articles