This is the "am I missing something obvious?" kind of question.

I would like to use backquotes in some way to make a value appear in a list only if it's not nil. So, for instance, given x, get '(1 2 3) if x is 2 and '(1 3) if x is nil. The following form will do the trick, but it looks convoluted:

`(1 ,@(if x (list x)) 3)

How can I do this another way, e.g., one that looks simpler? Obviously, I'm not interested in a solution using list functions.

  • Note that if x is unbound, you will get an error. Did you want to catch that case or is x always bound to something? Fundamentally, however, I don't think there is a simpler way to write it (although I'm a pedestrian Lisper, so YMMV).
    – NickD
    Jan 15 at 16:01
  • Sure, x will be bound. The code snippet would be in the body of a function, x an argument.
    – Augusto
    Jan 15 at 16:11
  • What you use is what I use, except I use and instead of if (as I think it's clearer). And I sometimes use a quoted list instead of invoking list (e.g. when there's no risk of modifying list structure). I know of nothing clearer, but perhaps someone will post something. To me, this is just an idiom to learn, use, and recognize. IOW, my answer to your question of missing something obvious is no, not that I'm aware of.
    – Drew
    Jan 15 at 18:30
  • an alternative to and in this case is when which some like better. and is also an idiom to learn, when you remember it evaluates to the last item when everything is true. I also don't know of another more obvious way to do it. Jan 15 at 21:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.