views:

117

answers:

1

Is there an easy way in Common Lisp to merge two plists? Or from another point of view: is there a way to remove duplicates from a plist? I know I can just append plists (and GETF will take the first one it finds), but I'd like to not keep accumulating unused keys as my app runs.

I'm thinking about something like (loop for p on my-plist by #'cddr ...), but there's often an easier way than my first thought!

+3  A: 

You could start from this primitive version:

(defun merge-plist (p1 p2)
  (loop with notfound = '#:notfound
        for (indicator value) on p1 by #'cddr
        when (eq (getf p2 indicator notfound) notfound) 
        do (progn
             (push value p2)
             (push indicator p2)))
  p2)

CL-USER 104 > (merge-plist '(a 1 b 2 c 3) '(a 2 b 4))
(C 3 A 2 B 4)
Rainer Joswig
You do not need `progn` after the `do`. :)
Svante
@Svante, I know. Sometimes I'm using it to make the group of expressions standout. It's also a syntax feature that I find sometimes puzzling for the human reader: DO expressions extend to the end. WHILE DO not.
Rainer Joswig