How do I add a number, say 2, to every item in a list?
(setq x '(1 2))
(+ 2 x)
(mapcar '2+ x)
(loop for i in x
do (+ 2 i))
(dolist (i x)
(+ 2 i))
None of the above work.
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.
Sign up to join this communityPossible solutions:
(mapcar (lambda (entry) (+ entry 2)) x)
(mapcar (apply-partially #'+ 2) x)
And if you need to update x
, then setq
it to the result of one of the above forms, e.g.:
(setq x (mapcar (apply-partially #'+ 2) x))
That's not very elegant (there's probably a much simpler answer) but this should work:
(setq x '(1 2 3 4))
(defun add-one (x)
"Add 1 to each element of list X"
(setq counter 0)
(setq res x)
(while (< counter (length x))
(setcar (nthcdr counter res) (1+ (car (nthcdr counter x))))
(setq counter (1+ counter)))
res)
(add-one x)
setcar
) a quoted constant list, such as '(1 2 3 4)
, otherwise the constant will be modified globally and the same code may behave differently in each run. Instead, either initialise x
to a new list, such as (list 1 2 3 4)
, before modifying it, or accumulate changes in a new list and set that as the value of x
, thus replacing its old value.
– Basil
Feb 11 '20 at 10:34
dolist
, mapc
, mapcar
, or successive calls to cdr
to go from one list element to another, without the need for indices or traversing the entire length each time. Lists are not random-access like arrays.
– Basil
Feb 11 '20 at 10:38
(+ 2 x)
doesn't work because+
takes numbers as arguments and returns their sum, and(mapcar '2+ x)
doesn't work because there is no built-in function called2+
(though you could define it yourself). The two loops work, but you are not saving the results of their computation anywhere, so the results are lost. – Basil Feb 11 '20 at 10:24