1

I have a variable with some common values between dap-mode debug templates and I want to use that variable along with other cons elements for :environment-variable in languages like Golang or Typescript you would do something like this:

variable = [1, 2, 3]
another_variable = [...variable, 4, 5, 6]

then another_variable will carry the value of [1, 2, 3, 4, 5, 6]

How can I do this in Emacs Lisp?

EDIT: I know how you can evaluate something inside a list, this is using the backquote, my problem was that I didn't know how Elisp processes lists in a fashion that keep the result plain because, for instance in Python, you can end with something like [1, [2, 3, 4]] if x is [1] and you do x.append([2, 3, 4]); I didn't know that ,@ was a thing and that neither append keeps a plain list.

3

2 Answers 2

6

You can use the backquote mechanism in combination with ,@ to splice the value of a variable into a list; or equivalently, use append:

(setq variable '(1 2 3))
(1 2 3)

(setq another-variable `(-2 -1 0 ,@variable 4 5 6))
(-2 -1 0 1 2 3 4 5 6)

;; or...
(setq another-variable (append '(-2 -1 0) variable '(4 5 6)))
(-2 -1 0 1 2 3 4 5 6)
0
1

Note: A Lisp program should not try to modify self-evaluating forms or constant lists (bug#40671). These are internal data structures [Message 42].

Be aware that the final argument for append is not copied.

ELISP> (setq var1 (vector 'a 'b))
ELISP> (symbol-value 'var1)
[a b]
ELISP> (setq lst (append var1 (list 1)))
ELISP> (symbol-value 'lst)
(a b 1)
8
  • Not sure exactly what you are objecting to, since in my example I do not modify existing list structure at all. I did not read all of the bug you referred to, but AFAICT all of the examples that are discussed involve modifying a "constant" list, which (I think) I'm not doing. How is the fact that append does not copy its final argument make any difference to the example in my answer?
    – NickD
    Commented Jul 16, 2020 at 14:37
  • @NickD: These objects are not explicitly modified, but neither should they be implicitly modifiable. You can modify the constant list through the variable: (setcar another-variable 0 'a).
    – user19761
    Commented Jul 16, 2020 at 15:30
  • So what? Are you proposing outlawing setcar and its ilk?
    – NickD
    Commented Jul 16, 2020 at 16:01
  • @NickD: no, I'm just saying it's better to assign a new list than a literal list. For instance, it is better to do this (setq lst (list 'a 'b)) rather than (setq lst '(a b)).
    – user19761
    Commented Jul 16, 2020 at 16:45
  • @NickD: The issue is that Elisp may "merge" literal objects so IMO it is better to not store literal objects in "variables".
    – user19761
    Commented Jul 16, 2020 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.