Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace item in association list in elisp

I have an alist in emacs lisp like:

(setq a1  '((:k1 . 1)    (:k2 . 2)    (:k3 . 3))) 

and i want to change value of :k1 to 10, like (:k1 . 10). How do i do that?

I tried (setf (assoc :k1 a1) '(:k1 . 10)) - it didn't work.

like image 212
Mirzhan Irkegulov Avatar asked Apr 08 '12 13:04

Mirzhan Irkegulov


2 Answers

With alists, you usually add a new cons in front of the old one to "shadow" the old value, like so:

(add-to-list 'a1 '(:k1 10)) 

After you do this (assoc :k1 a1) will return 10.

If you want to "undo" your change so assoc again returns your old value, use this code:

(setq a1 (delq (assoc :k1 a1) a1)) 

This will remove the FIRST match for :k1 from a1.

like image 178
krzysz00 Avatar answered Oct 05 '22 18:10

krzysz00


As of Emacs 25.1, alist-get is a place form so you can do:

(setf (alist-get :k1 a1) 10) 
like image 42
Dale Avatar answered Oct 05 '22 18:10

Dale