Affect one list item

If I have a list of numbers

(setq numbers '(10 11 12)) 

and I want to increase, say, the third number, I can do this:

 (setf (nth 2 numbers) (1+ (nth 2 numbers))) 

But I do not like to repeat "(nth 2 numbers)". Is there a way I can write this, but have only one link to "(nth 2 numbers)"?

+4
source share
3 answers

There is a macro for this:

 (incf (nth 2 numbers)) 

You can specify the value to be added as an optional argument.

+5
source

If you need a more general answer (for example, for some other function than 1+ ), you probably want to look at cl-callf . Another option is to use gv-ref and gv-deref , but this doesnโ€™t seem to be suitable for your business (this is rarely good, actually).

+2
source

There is a pure emacs lisp way to do this without double calling nth ...

 (defun inc-list(n lst) (let ((nc (nthcdr n lst))) (setcar nc (1+ (car nc))) lst)) 
+1
source

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


All Articles