lispelispquote

How to use a function in setq with quote?


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?


Solution

  • 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.