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

3

5

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!

Tarahtaran answered 5/8, 2013 at 15:32 Comment(2)
Not really part of your question, but you may be find the difference between set, setq and setf interesting.Dermatogen
That is interesting, thanks! +1 because it was sort of a question-within-the-question. :)Tarahtaran
O
14

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

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

For more details see reference.

Onetoone answered 5/8, 2013 at 15:50 Comment(2)
Note that arrays in Common Lisp are conceptually really multidimensional, not just arrays of arrays. That is why there is a single aref operation, not nested ones.Yellowish
Note that the linked reference (Common Lisp the Language, 2nd edition, often referred to as CLtL2) is somewhat outdated. The references to the HyperSpec in other answers are more authoritative for Common Lisp.Ogilvy
C
7

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
Chronology answered 5/8, 2013 at 17:34 Comment(0)
C
4

The correct invocation is

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

setq is used when you're assigning to a variable. Only setf knows how to "reach into" compound objects as with setting a value in your array. Of course, setf also knows how to assign to variables, so if you stick with setf you'll always be okay.

Calash answered 5/8, 2013 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.