Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elisp - Loop over an alist

Tags:

emacs

elisp

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)) 
like image 734
Joe Avatar asked Dec 14 '11 21:12

Joe


2 Answers

cl-loop from cl-macs.el has support for destructing like CL:

(cl-loop for (key . value) in my-list       collect (cons value key)) 
like image 87
Jürgen Hötzel Avatar answered Sep 28 '22 10:09

Jürgen Hötzel


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))) 
like image 36
ataylor Avatar answered Sep 28 '22 09:09

ataylor