help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Add/remove an element into/from a cons.


From: Tassilo Horn
Subject: Re: Add/remove an element into/from a cons.
Date: Tue, 26 Oct 2021 08:22:31 +0200
User-agent: mu4e 1.7.4; emacs 29.0.50

Hongyi Zhao <hongyi.zhao@gmail.com> writes:

>> This would add it again as the last element:
>>
>> --8<---------------cut here---------------start------------->8---
>> (let ((place (assoc 'company-tabnine th/test)))
>>   (setf place (append place '(company-ispell))))
>> --8<---------------cut here---------------end--------------->8---
>
> Thanks. But the push doesn't work:
>
> (let ((place (assoc 'company-tabnine th/test)))
>   (setf place (push place '(company-ispell))))

Have a look at the docs.  `push' wants the place as second element, and
then you don't need the `setf' anyway.

--8<---------------cut here---------------start------------->8---
(let ((place (assoc 'company-tabnine th/test)))
  (push 'company-ispell place))
--8<---------------cut here---------------end--------------->8---

But note that `push' will add it to the front of the list.

Hm, I just saw that none of my code actually works, i.e., it does not
alter the value of `th/test'.

--8<---------------cut here---------------start------------->8---
(setq th/test '((company-tabnine :separate company-capf company-dabbrev 
company-keywords company-files company-ispell)))

(let ((place (assoc 'company-tabnine th/test)))
  (setf place (remove 'company-ispell place)))

(let ((place (assoc 'company-tabnine th/test)))
  (setf place (append place '(company-ispell))))

(let ((place (assoc 'company-tabnine th/test)))
  (push 'company-ispell place))
--8<---------------cut here---------------end--------------->8---

Aren't alist entries setf-able places?  It seems so, at least:

(let ((val (assoc 'company-tabnine th/test)))
  (setf (assoc 'company-tabnine th/test)
        (remove 'company-ispell val)))

signals a void-function error.

Ah, now I got it.  You must use `alist-get' instead of `assoc' and not
bind the place to a variable but use it explicitly as the first argument
of `setf' which makes sense given that `setf' is a macro determining the
place from its first argument.  So these do actually work:

--8<---------------cut here---------------start------------->8---
(setf (alist-get 'company-tabnine th/test)
      (remove 'company-ispell (alist-get 'company-tabnine th/test)))

(setf (alist-get 'company-tabnine th/test)
      (append (alist-get 'company-tabnine th/test)
              '(company-ispell)))

(push 'company-ispell (alist-get 'company-tabnine th/test))
--8<---------------cut here---------------end--------------->8---

Bye,
Tassilo



reply via email to

[Prev in Thread] Current Thread [Next in Thread]