Easy way to merge plists?
Asked Answered
L

1

7

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!

Logical answered 3/8, 2010 at 16:31 Comment(2)
How do you want to handle duplicate keys with different values? Does one of the lists take precedence?Heintz
The easiest way to remove duplicates from a plist is to start with make-hash-table ...Brag
T
5

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)
Tenor answered 3/8, 2010 at 21:23 Comment(2)
You do not need progn after the do. :)Heintz
@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.Tenor

© 2022 - 2024 — McMap. All rights reserved.