1

Suppose I'm setting a var like this:

(setq var '((:item1 "stringA") (:item2 "stringB")))

(this works)

Now I would like "stringA" be a conditional, like this:

(setq var '((:item1 (if (> 6 (string-to-number (format-time-string "%u")))
                     "stringA"
                     "stringC"))
            (:item2 "stringB") ))

This doesn't work, likely due to the quote operator (or function?). How should it be written to work?

1
  • Don't use setq unless you need to port code to dialects that need it. setf works on everything setq is a form of setf whose argument must be a symbol. BUT! if the argument is a symbol macro, it will still work. You can't do (setq (car x) 42) but if c is a symbol macro which expands to (car x), you can do (setq c 42); it will store to (car x)! setq: just historical baggage from 1960 LISP in which a variable was set using (set 'var value) and so setq was invented to add the quote for you: so you could just (setq var value). Commented Apr 12 at 18:10

1 Answer 1

6

Nothing inside a quoted list is evaluated. You have to call functions to construct the list dynamically:

(setq var 
      (list (list :item1
                  (if (> 6 (string-to-number (format-time-string "%u")))
                      "stringA" "stringC"))
            '(:item2 "stringB")))

or you can use backquote to specify the parts of the list that should be literal and evaluated.

(setq var
      `((:item1 
         ,(if 
           (> 6 (string-to-number (format-time-string "%u")))
           "stringA" "stringC"))
        (:item2 "stringB") ))

Inside a backquoted expression, comma (which looks like an upside-down quote) marks an expression that should be evaluated.

Sign up to request clarification or add additional context in comments.

4 Comments

This seems to work for my case. Please clarify what the changes are: (1) single-quote needs to be changed to backquote (back-tick), (2) function call is preceded by a comma. Any caveats on changing single-quote to back-tick?
When using backquote, it's unspecified which parts of the result might share with the list structure in the source code. You should generally treat it all as literal, so not try to modify it in place, just like a quoted list.
But when you call functions like LIST and CONS you know they return fresh, modifiable list structure.
@AlexanderShcheblikin: (2) isn't about function calls specifically. When you use a comma in a backquoted form, the form immediately following the comma is evaluated and the result of that evaluation is substituted into the backquoted form. The form to be evaluated can be any valid lisp form.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.