Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

common lisp how to set an element in a 2d array?

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

My start condition is this:

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

I want to alter, say, the 2nd item of the 3rd "row" to give this:

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

The following, which I would have thought close, gives an error:

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

So what's the correct syntax?

Thanks!

like image 761
Olie Avatar asked Nov 28 '22 02:11

Olie


2 Answers

I think proper way is to use setf with aref like this:

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

For more details see reference.

like image 192
MAnyKey Avatar answered Dec 05 '22 02:12

MAnyKey


You can find a dictionary of the ARRAY operations in the 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) are documented here:

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

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

Basically if you want to set 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 set operation is schematically:

(setf <accessor code> new-content)

This means here:

(setf (aref my-array 4 5 2) 'foobar)   ; set the content of the array at 4,5,2 to
                                       ; the symbol FOOBAR
like image 37
Rainer Joswig Avatar answered Dec 05 '22 01:12

Rainer Joswig