常见的lisp如何在二维数组中设置一个元素?

Oli*_*lie 4 common-lisp multidimensional-array

我想我只是使用setq(或者setf,我不确定区别),但我不明白如何[i][j]在lisp中引用数组中的-th元素.

我的开始条件是这样的:

? (setq x (make-array '(3 3)))
#2A((0 0 0) (0 0 0) (0 0 0))
Run Code Online (Sandbox Code Playgroud)

我想改变第三行"第二行"中的第二项来表示:

? ;;; What Lisp code goes here?!
#2A((0 0 0) (0 0 0) (0 "blue" 0))
Run Code Online (Sandbox Code Playgroud)

以下,我认为接近,给出一个错误:

(setq (nth 1 (nth 2 x)) "blue")
Run Code Online (Sandbox Code Playgroud)

那么正确的语法是什么?

谢谢!

MAn*_*Key 15

我认为正确的方法是使用setf具有aref这样的:

(setf (aref x 2 1) "blue")
Run Code Online (Sandbox Code Playgroud)

欲了解更多详情,请参见参考.

  • 请注意,Common Lisp中的数组在概念上实际上是多维的,而不仅仅是数组的数组.这就是为什么有一个`aref`操作,而不是嵌套操作. (4认同)

Rai*_*wig 7

您可以ARRAY在Common Lisp HyperSpec中找到操作字典(ANSI Common Lisp标准的Web版本:

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

AREF(SETF AREF)记录在这里:

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

设置数组元素的语法是:(setf (aref array &rest subscripts) new-element).

基本上如果你想在Common Lisp中设置一些东西,你只需要知道如何获得它:

(aref my-array 4 5 2)  ; access the contents of an array at 4,5,2.
Run Code Online (Sandbox Code Playgroud)

然后设置操作示意图:

(setf <accessor code> new-content)
Run Code Online (Sandbox Code Playgroud)

这意味着:

(setf (aref my-array 4 5 2) 'foobar)   ; set the content of the array at 4,5,2 to
                                       ; the symbol FOOBAR
Run Code Online (Sandbox Code Playgroud)