gpt4 book ai didi

clojure - 更好的序列重复去除器

转载 作者:行者123 更新时间:2023-12-01 08:57:36 25 4
gpt4 key购买 nike

我做了这个函数来删除连续的重复,但我想知道是否有更好或更短的方法来使用 distinct 或类似的东西来表达它。

(defn duplicates
[s]
(reduce
#(if-not (= (last %1) %2)
(conj %1 %2) %1)
[] s))

最佳答案

clojure-1.7.0-alpha1 在名称 dedupe 下具有此函数的正确版本.

你引用的那个返回它的输入序列,没有连续的重复。 (几乎可以肯定)不知不觉中,如果它们开始输入序列,它也会吞下所有连续的 nil 值。

#(if-not (= (last %1) %2)
(conj %1 %2)
%1)

要减少的 lambda 表示:如果累加器的最后一个元素 (%1) 不等于下一个输入元素 (%2),则将其添加到累加器,否则返回累加器。

因为 (last []) 的计算结果为 nil,所以当累加器为空时,它永远不会添加 nil 值。我把修复这个问题留给读者作为练习:

确保 duplicates 为输入 [nil nil true true nil] 返回预期结果 [nil true nil]

注意:使用矢量操作时,使用 peek 的性能明显优于 last

EDIT(因为您编辑了问题):distinct 只返回输入序列的每个值一次。与 set 不同,它返回惰性序列。

duplicates/dedupe 的一种更惯用的编写方式是 A. Webb 作为评论发布的方式(因为它也是懒惰的)。否则,修复 lambda 以使用空累加器作为其输入正确工作并使用 peek 而不是 last 会更惯用。

clojure-1.7.0-alpha1 中,您将使用 dedupe 转换器进行即时评估,而不是修复 lambda,例如。 g.:

(into [] (dedupe) [nil nil true true nil])
-> [nil true nil]

或者对于惰性求值:

(dedupe [nil nil true true nil])
-> (nil true nil)

关于clojure - 更好的序列重复去除器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25552506/

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