Return elements if they are in two given lists in

2019-08-16 06:20发布

How can i return elements if they are in two given lists?

Example:

L1 = (a b c d e a b c)

L2 = (a d f g k c c)

Result = (a a a c c c c d d)

I want to remove elements that arent in both lists and, then, append the resultant lists

标签: lisp
1条回答
男人必须洒脱
2楼-- · 2019-08-16 06:50

You can start with a hash table, mapping a list element to a pair, first being elements from the first list, second - elements from the second. Then you collect the elements:

(defun common-elements (l1 l2 &key (test 'eql))
  (let ((ht (make-hash-table :test test)) ret)
    (dolist (e l1)
      (let ((pair (gethash e ht)))
        (if pair
            (push e (car pair))
            (setf (gethash e ht) (cons (list e) nil)))))
    (dolist (e l2)
      (let ((pair (gethash e ht)))
        (when pair ; no need to store e when it is not in l1
          (push e (cdr pair)))))
    (maphash (lambda (e pair)
               (declare (ignore e))
               (when (cdr pair) ; we know (car pair) is non-nil
                 (setq ret (nconc (car pair) (cdr pair) ret))))
             ht)
    ret))
(common-elements '(a b c d e a b c) '(a d f g k c c))
==> (A A A C C C C D D)

Note that the order in which the list elements are returned is not defined.

查看更多
登录 后发表回答