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?

ideasman42
  • 8,375
  • 1
  • 28
  • 105
  • 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 '19 at 06: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 '19 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 '19 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 '19 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 '19 at 16:58
  • The same feature solves both answers, but for a beginner its not obvious that this is possible. Said differently - I wouldn't have been able to get the answer given here from reading the other answer. – ideasman42 Mar 17 '19 at 23:11
  • Now much more experienced in elisp and I still don't think this is a duplicate, the other question touches on similar areas but isn't about declaring a list literal. Just because the same language feature happens to work in both cases - doesn't make the question a duplicate IMHO. Especially as `(cons x y)` is a valid answer in that case which is related to quoting variables. – ideasman42 Jan 15 '23 at 23:41

1 Answers1

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)
xuchunyang
  • 14,302
  • 1
  • 18
  • 39