常见Lisp中的指针 [英] Pointers in Common Lisp
问题描述
我想保存对我保存在另一个变量中的某些数据的一部分的引用(指针):
I want to save a reference (pointer) to a part of some Data I saved in another variable:
(let ((a (list 1 2 3)))
(let ((b (car (cdr a)))) ;here I want to set b to 2, but it is set to a copy of 2
(setf b 4))
a) ;evaluates to (1 2 3) instead of (1 4 2)
我可以使用宏,但是如果我想在列表中间更改某些数据,那么我将需要执行很多代码,而且我也不是很灵活:
I could use macros, but then there would ever be much code to be executed if I want to change some Data in the middle of a list and I am not very flexible:
(defparameter *list* (create-some-list-of-arrays))
(macrolet ((a () '(nth 1000 *list*)))
(macrolet ((b () `(aref 100 ,(a))))
;; I would like to change the macro a here if it were possible
;; but then b would mean something different
(setf (b) "Hello")))
是否可以将变量创建为引用而不是副本?
Is it possible, to create a variable as a reference and not as a copy?
推荐答案
cl-user> (let ((a '(1 2 3)))
(let ((b (car (cdr a))))
(setf b 4))
a)
;Compiler warnings :
; In an anonymous lambda form: Unused lexical variable B
(1 2 3)
cons
单元格是一对指针. car
取消引用第一个,而cdr
取消引用第二个.您的列表实际上是
A cons
cell is a pair of pointers. car
dereferences the first, and cdr
dereferences the second. Your list is effectively
a -> [ | ] -> [ | ] -> [ | ] -> NIL
| | |
1 2 3
在您定义b
的顶部,(cdr a)
使您获得第二个箭头.取其中的car
会取消引用该第二个单元格的第一个指针,并将其值交给您.在这种情况下,为2
.如果要更改该指针的值,则需要setf
而不是其值.
Up top where you're defining b
, (cdr a)
gets you that second arrow. Taking the car
of that dereferences the first pointer of that second cell and hands you its value. In this case, 2
. If you want to change the value of that pointer, you need to setf
it rather than its value.
cl-user> (let ((a '(1 2 3)))
(let ((b (cdr a)))
(setf (car b) 4))
a)
(1 4 3)
这篇关于常见Lisp中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!