Elisp: How to delete an element from an association list with string key

后端 未结 4 1282
执念已碎
执念已碎 2021-02-07 06:54

Now this works just fine:

(setq al \'((a . \"1\") (b . \"2\")))
(assq-delete-all \'a al)

But I\'m using strings as keys in my app:



        
4条回答
  •  花落未央
    2021-02-07 07:16

    Emacs 27+ includes assoc-delete-all which will work for string keys, and can also be used with arbitrary test functions.

    (assoc-delete-all KEY ALIST &optional TEST)
    
    Delete from ALIST all elements whose car is KEY.
    Compare keys with TEST.  Defaults to ‘equal’.
    Return the modified alist.
    Elements of ALIST that are not conses are ignored.
    

    e.g.:

    (setf ALIST (assoc-delete-all KEY ALIST))
    

    In earlier versions of Emacs, cl-delete provides an alternative:

    (setf ALIST (cl-delete KEY ALIST :key #'car :test #'equal))
    

    Which equivalently says to delete items from ALIST where the car of the list item is equal to KEY.

    n.b. The answer by Kaz mentions this latter option already, but using the older (require 'cl) names of delete* and remove*, whereas you would now (for supporting Emacs 24+) use cl-delete or cl-remove (which are auto-loaded).

提交回复
热议问题