Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a common LISP function to compare the contents of two lists?

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

like image 641
damonkashu Avatar asked Nov 05 '10 22:11

damonkashu


2 Answers

If order isn't important, you can use equal. For instance,

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

is true. Thus one way to do it would be to (sort) the list and then use equal. Note that sort is destructive so if order matters, you might want to copy it first.

like image 145
Steve Rowe Avatar answered Oct 14 '22 20:10

Steve Rowe


(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))))
like image 41
huaiyuan Avatar answered Oct 14 '22 21:10

huaiyuan