0

When writing an alist where all the key/value pairs have keys that are variables, is there a convenient way to write this in Elisp without repetition?

eg:

`((foo . ,foo)
  (long-variable-name . ,long-variable-name)
  (yet-another-long-variable-name . ,yet-another-long-variable-name)
  (you-get-the-idea . ,you-get-the-idea))

So the same structure could be written as:

(alist-from-vars
  foo
  long-variable-name
  yet-another-long-variable-name
  you-get-the-idea)

... with an arbitrary number of arguments.

3

If you don't want to quote the variable, you need to use a macro instead of a function, e.g.,

(defmacro alist-from-vars (&rest vars)
  `(list ,@(mapcar (lambda (var) `(cons ',var ,var))
                   vars)))

(macroexpand '(alist-from-vars a b))
;; => (list (cons (quote a) a) (cons (quote b) b))

(let ((a 1)
      (b 2))
  (alist-from-vars a b))
;; => ((a . 1) (b . 2))
2

I don't get exactly what you're trying to get, but maybe this at least helps you find the way:

(defun alist-from-vars (&rest vars)
  (mapcar (lambda (x) `(,x . ,(symbol-value x))) vars))

(let ((a 12)
      (b 24)
      (c 7))
  (alist-from-vars 'a 'b 'c))
1
  • 1
    You can just write (cons x (symbol-value x)) in your lambda . More readable.
    – Tom
    Jan 21 '20 at 19:44

Your Answer

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

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