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

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

Re: How to delete all nil properties from a plist?


From: Pascal J. Bourguignon
Subject: Re: How to delete all nil properties from a plist?
Date: Sun, 02 Aug 2015 01:43:42 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux)

Marcin Borkowski <address@hidden> writes:

> Hi all,
>
> so I'm still using plists, though I'm less and less sure that they are
> actually better than alists for my use-case.  Now I need to delete all
> properties whose value is nil.  I'm using this function:
>
> (defun plist-clear (plist)
>   "Return PLIST with all nil properties deleted."
>   (cond
>    ((< (length plist) 2) nil)

very bad, you walk the list once more.

>    ((null (cadr plist)) (cddr plist))

ok.

>    (t (cons (car plist) (cons (cadr plist) (plist-clear (cddr
>    plist)))))))

And since you call plist-clear recursive, the above walk makes it O(n²)!


> Question 1: is there a better way to write it?  (Especially the last
> line.)

Yes.

(defun plist-clear (plist)
  "Return PLIST with all nil properties deleted."
  (loop for (k v) on plist by (function cddr)
        when v
        collect k collect v))
 
> Question 2: how would I do the analogous thing with alists?

(defun alist-clear (alist)
  "Return ALIST with all nil properties deleted."
  (remove* nil alist :key (function cdr)))


-- 
__Pascal Bourguignon__                 http://www.informatimago.com/
“The factory of the future will have only two employees, a man and a
dog. The man will be there to feed the dog. The dog will be there to
keep the man from touching the equipment.” -- Carl Bass CEO Autodesk


reply via email to

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