Is there a general LISP function for comparing the contents of two lists?

In particular, I just want to make sure that the two lists have the same elements, ignoring the order

+7
lisp common-lisp
source share
6 answers

According to Steele, set-difference returns a list of list1 elements that are not displayed in list 2. This operation is not destructive.

So, if the difference in values ​​is empty and the lengths are the same ...

http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node152.html#SECTION001950000000000000000

+2
source share

If order is not important, you can use equal. For example,

(equal (list 1 2) (list 1 2)) 

truly. Thus, one way to do this is to (sort) a list, and then use an equal. Note that sorting is destructive, so if the order matters, you can copy it first.

+6
source share
 (defun same-bag-p (bag1 bag2 &key (test #'eql)) (let ((table (make-hash-table :test test))) (loop for key in bag1 do (incf (gethash key table 0))) (loop for key in bag2 do (decf (gethash key table 0))) (loop for val being each hash-value of table always (= val 0)))) 
+4
source share

If duplicate items are not important, see also SET-EXCLUSIVE-OR.

+2
source share

If the order is not important, you can use the "equal set":

(equal sets (1 2) (1 2)) β†’ T

(equal sets (1 2) (2 1)) β†’ T

(equal sets (1 2 5) (1 2)) β†’ NIL

(equal sets (1 2) (1 5 2)) β†’ NIL

+1
source share

Sort both lists, then compare:

 (equal (sort l1 #'<) (sort l2 #'<)) 
0
source share

All Articles