Common Lisp中的线性递归列表差异函数
-
03-07-2019 - |
题
我正在浏览这个有趣的教程,并坚持他说的最后一件事,“练习:给出联合和差异的线性递归实现。” (列表)
联盟,没有汗水。差异,汗水。
尝试看起来像这样。 。
(defun list-diff (L1 L2)
(cond
((null L1) L2)
((null (member (first L1) L2)) (cons (first L1) (list-diff (rest L1) L2)))
(t (list-diff (rest L1) L2))
)
)
现在,它返回L1中不在L2中的所有元素,但它只返回所有L2(显然)。类似地,如果我将第3行中的L2更改为“nil”,则它只返回不在L2中但不包含L2的所有L1。
我在解决方法上的尝试看起来并不是递归的,当它们出现时,我最终会得到堆栈溢出(就像我尝试在某处调用(list-diff L2 L1))。
他的任何其他练习,例如list-intersection,只需要遍历L1的元素。在这里,我想从L2中运行关键元素,或者运行(list-diff L2 L1),然后将两者的结果联合起来,但这不再是线性递归。
思考?
(不是功课,真的。我以为我会试着看一些LISP的乐趣。)
编辑:基于响应正确执行此操作的函数是:
(defun list-diff (L1 L2)
(cond
((null L1) nil)
((null (member (first L1) L2)) (cons (first L1) (list-diff (rest L1) L2)))
(t (list-diff (rest L1) L2))
)
)
其他提示
在Lisp中,这是'set difference'的定义:
set-difference list1 list2 &key (test #'eql) test-not (key #'identity)
Function
Returns a list of elements of list1 that do not appear in list2.
这是你修改过的实现:
(defun list-diff (L1 L2)
(cond
((null L1) L1)
((member (first L1) L2) (list-diff (rest L1) L2))
(t (cons (first l1) (list-diff (rest l1) l2)))))
不隶属于 StackOverflow