如何解决Lisp:两个列表的有序并集
我正在尝试创建一个以有序方式返回两个列表的并集的函数。 这是我的代码:
(defun setunion (lst1 lst2)
(cond
((null lst1) lst2)
((null lst2) lst1)
((member (car lst2) lst1)
(setunion lst1 (cdr lst2)))
(t (append (setunion lst1 (cdr lst2))
(list (car lst2))))))
(print (setunion '(a b c) '(a c d e f a)))
这将返回(A B C F E D),但我正在寻找的输出是(A B C D E F)。如何更改代码以返回正确的输出?
谢谢!
编辑:我想出来了。我做了一个辅助函数,它删除了列表2的重复项并对其进行了反向处理,还删除了列表1的重复项。
(defun help (lst1 lst2)
(setunion (remove-duplicates lst1 :from-end t) (reverse(remove-duplicates lst2 :from-end t))))
(print (help '(b c b d) '(a d e a)))
这就是我正在寻找的输出(B C D A E)。
解决方法
好,所以基本上您要做的就是删除所有列表中的重复项,并且元素应该按照首次出现的顺序排列。您可以附加所有列表,然后从末尾删除重复项:
(defun set-union (&rest lists)
(remove-duplicates (reduce #'append lists)
:from-end t))
,
如果您想要的是一堆列表的并集,以使列表中的元素按照它们在列表中出现的顺序出现(从左开始),那么这是一种很自然的方法。我不确定这是否是我在现实生活中写的东西。它的优点是:
- 很容易看到正在发生的事情;
- 它不依赖多毛的标准CL函数。
它具有缺点,需要长尾消除才能使用长列表(有些人认为这样的代码不是惯用的CL)。
$mailer->send($email);
这是一个使用显式迭代的版本,但在其他方面也有相同的技巧。
(defun union-preserving-order (&rest ls)
;; Union of a bunch of lists. The result will not contain
;; duplicates (under EQL) and elements will occur in the order they
;; occur in the lists,working from the left to the right. So
;; (union-preserving-order '(a b) '(b a c)) will be (a b c),as will
;; (union-preserving-order '(a b) '(c b a)),while
;; (union-preserving-order '(b a) '(a b c) '(c d)) will be (b a c
;; d).
(upo/loop (first ls) (rest ls) '()))
(defun upo/loop (lt more accum)
;; LT is the list we're working on,MORE is more lists for later,;; ACCUM is the list we're building (backwards). In real life this
;; would be a local function in UNION-PRESERVING-ORDER.
(if (null lt)
;; Finished this list
(if (null more)
;; no more lists: we're done
(nreverse accum)
;; more lists,so pick the first of them and loop on that
(upo/loop (first more) (rest more) accum))
;; not finished this list,so loop on it
(upo/loop (rest lt) more
;; Either the next element of this list is already in
;; the accumulator,or it's not and we need to add it.
(if (member (first lt) accum)
accum
(cons (first lt) accum)))))
最后,这是一个肮脏的hack,它可以将结果转发出去。如果没有证据,我认为这在性能方面是最好的,而无需借助诸如哈希表之类的巧妙查找结构来检查您是否已经看过元素。
(defun union-preserving-order (&rest ls)
;; Union of a bunch of lists. The result will not contain
;; duplicates (under EQL) and elements will occur in the order they
;; occur in the lists,while
;; (union-preserving-order '(b a) '(a b c) '(c d)) will be (b a c
;; d).
(let ((accum '()))
(dolist (l ls (nreverse accum))
(dolist (e l)
(pushnew e accum)))))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。