3

Given a list literal '(1 2 3)

is it possible to conditionally include parts of the list?

eg:

'(1 2 3
  (when thing-is-true '(10 11 12)))
  4 5 6)

Which would result in

'(1 2 3 4 5 6) or '(1 2 3 10 11 12 4 5 6) dependent on thing-is-true.


Python for example supports:

[1, 2, 3, *([10, 11, 12] if thing_is_true else []), 4, 5, 6]

What is the most straightforward way to achieve this using a single expression, without first defining variables and them into a list?

7
  • Don't think this is a duplicate because I'm not asking about adding items to a list. Rather, how to declare a list. Also notice the answer to this question is quite different.
    – ideasman42
    Mar 17, 2019 at 6:43
  • Hmm, I guess there is minor difference in that the dup's answer doesn't mention ,@, only ,; but to my mind the answer in both cases is essentially: "you're looking for backquote".
    – npostavs
    Mar 17, 2019 at 13:08
  • I was aware of the feature (that it could be useful in this case), I just didn't know how to use it because I'm not that experienced in elisp.
    – ideasman42
    Mar 17, 2019 at 13:26
  • 1
    I'm not aware of what you're aware of, I just talk about what's written in the question and vote accordingly.
    – npostavs
    Mar 17, 2019 at 13:50
  • 1
    Seems like a dup to me, regardless of a minor difference in what you're trying to do. The question is really about a misunderstanding, and the referenced duplicate Q&A covers that. (And the tags should include quote and not include elisp, IMO.)
    – Drew
    Mar 17, 2019 at 16:58

1 Answer 1

3

You can use the macro (elisp) Backquote, e.g.,

`(1 2 3 ,@(when nil '(10 11 12)) 4 5 6)
;; => (1 2 3 4 5 6)

`(1 2 3 ,@(when t '(10 11 12)) 4 5 6)
;; => (1 2 3 10 11 12 4 5 6)

if you expand the above macros, they are simply using append

(append '(1 2 3) (when nil '(10 11 12)) '(4 5 6))
;; => (1 2 3 4 5 6)

(append '(1 2 3) (when t '(10 11 12)) '(4 5 6))
;; => (1 2 3 10 11 12 4 5 6)

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