gpt4 book ai didi

list - 普通口齿不清 : Removing elements with the same cdr

转载 作者:太空宇宙 更新时间:2023-11-03 18:56:04 24 4
gpt4 key购买 nike

(作业帮助,对我放轻松)(我必须在不使用破坏性函数(setf)的情况下执行此操作)

使用普通的 lisp,作为一些代码的一部分,我需要能够:

获取列表列表,比较2个元素的cdr,如果等于忽略第一个元素,如果不相等,则尝试将第一个元素与列表中下一个未选中的元素进行比较。

一些例子来说明:

((1 1 1) (2 1 1) (3 1 1)) -> ((3 1 1))

((2 2 0) (4 1 1) (1 2 0) (3 0 1) (8 1 1)) -> ((1 2 0) (3 0 1) (8 1 1))

(defun simplify2 (vari)
;If last term: stop
(if (equal (cdr vari) nil) vari

;If cdr of first and second term are equal...
(if (equal (cdar vari) (cdr (cadr vari)))

;Ignore the first term and continue with the rest of the list
(simplify2 (cdr vari))

;Otherwise (this is the line which isn't working)
(cons (car vari) (simplify2 (cdr vari))))))

目前,只有当列表中所有“类似”字词并排放置时,代码才能正常工作。

最佳答案

Le Petit Prince's suggestion在评论中使用 remove-duplicates 可能是您想要的。 remove-duplicates 是非破坏性的(参见 delete-duplicates 可能是破坏性的),它被指定为返回一个新列表,其中除最后一个实异常(exception)的所有实例省略了一个元素(添加了强调):

remove-duplicates

remove-duplicates returns a modified copy of sequence from which any element that matches another element occurring in sequence has been removed. … The elements of sequence are compared pairwise, and if any two match, then the one occurring earlier in sequence is discarded, unless from-end is true, in which case the one later in sequence is discarded.

您需要指定一个 key 参数来表明实际比较的是元素的 cdr 和一个 test 参数来表明它们应该与 equal 进行比较。因此:

(remove-duplicates '((1 1 1) (2 1 1) (3 1 1))
:test 'equal
:key 'cdr)
;=> ((3 1 1))

(remove-duplicates '((2 2 0) (4 1 1) (1 2 0) (3 0 1) (8 1 1))
:test 'equal
:key 'cdr)
;=> ((1 2 0) (3 0 1) (8 1 1))

关于list - 普通口齿不清 : Removing elements with the same cdr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27386201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com