0

How can i increment a variable in a local function and the change to persist ?

(defun inc(x) (+ x 1))

(setq a 1)

I want this (inc a) to change the value of a to 2

I searched this problem , and i find something with setf but i couldn't resolve the problem.

user3052078
  • 487
  • 1
  • 8
  • 20

1 Answers1

3

Depending on your exact problem, this may be answered in Variable references in lisp, which discusses the particular issues of lexical scope that you may be encountering. It even uses the same example of incrementing the value of a variable, so it's particularly relevant.

However, if you're just looking for how to increment a value, then you may be interested in the standard function 1+, where (1+ x) is equivalent to (+ x 1), and the macro incf for incrementing the value of a place by 1.

(let ((a 1))      (let ((a 1))
  (1+ a))           (incf a)
                    a)
;=> 2             ;=> 2

However, depending on exactly what you're trying to do, these might not work for you (and the possible duplicate is more appropriate). If you're trying to call a function with the value of a variable, and then have the body of the function effect a change in the binding of the variable, then you can't do it. That is, there is no function that can make this work:

(let ((a 1))
  (foo a)
  a)
;=> 2

The function foo is called with the value of the variable a, which is the number 1; it doesn't have any access to the variable, so it can't bind the variable to a new value. However, a macro can work with the unevaluated forms it is called with, so you can have the sort of side effects that you may be looking for. E.g.:

(let ((a 1))
  (incf a)
  a)
;=> 2

However, as explained above, you can't do:

(defun my-incf (x)
  (incf x))         ; modifies the binding of x

(let ((a 1))
  (my-incf a)
  a)
;=> 2

because the call to incf changes the binding of x, which is a variable that is local to my-incf.

Community
  • 1
  • 1
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353