How to mutate a global variable passed and mixed inside a function?

I am wondering how to permanently change the value of a global variable from within a function without using the variable name inside the function, i.e.:

(defvar *test1* 5)
(defun inctest (x) (incf x))
(inctest *test1*) ;after it runs, *test1* is still 5, not 6

According to this :

if the object passed to the function is changed and you change it in the function, the changes will be visible to the caller, as the caller and the callee will refer to the same object.

Isn't that what I'm doing above?

+3
source share
4 answers

If you want it to inctestbe a function, pass it the name of the global variable.

(defun inctest (x) (incf (symbol-value x)))
(inctest '*test1*)
+1
source

, , .. , . x, , .

, , , , . , , , , :

(defvar *test2* (list 5))
(defun inctest2 (x) (incf (car x)))
(inctest2 *test2*)
*test2* ; => (6)
+2

Common Lisp "", . , .

, (a symbol), symbol-value / :

(defvar *test1* 42)

(defun inctest (varname)
  (incf (symbol-value varname)))

(inctest '*test1*) ;; Note we're passing the NAME of the variable

, , , , , :

(defun inctest (accessor)
  (funcall accessor (1+ (funcall accessor))))

(let ((x 42))
  (inctest (lambda (&optional (value nil value-passed))
             (if value-passed
                 (setf x value)
                 x)))
  (print x))

:

(defmacro accessor (name)
  (let ((value (gensym))
        (value-passed (gensym)))
  `(lambda (&optional (,value nil ,value-passed))
     (if ,value-passed
         (setf ,name ,value)
         ,name))))

 (let ((x 42))
   (inctest (accessor x))
   (print x))
+1

, , .

, , : (incf *test1*)

: , , , :

(defmacro my-incf (variable-name)  
  `(incf ,variable-name))
0

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


All Articles