What's the best way to loop over an alist and do something with each pair in Emacs Lisp? I suppose a macro wouldn't be difficult, I'm just wondering if this is built in somewhere. Is there a more elegant way than below?
(setq my-list '((a . 1) (b . 2) (c . 3))) (loop for key in (mapcar 'car my-list) for value in (mapcar 'cdr my-list) collect (cons value key)) ;; Returns this ((1 . a) (2 . b) (3 . c))
cl-loop from cl-macs.el has support for destructing like CL:
(cl-loop for (key . value) in my-list collect (cons value key))
Another way to do this without loop
is with mapcar
and a lambda. I don't think it's any more elegant, but it's more idiomatic for elisp as opposed to Common Lisp:
(mapcar (lambda (element) (let ((key (car element)) (value (cdr element))) (cons value key))) '((1 . a) (2 . b)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With