如何在集合中使用Clojure的distinct()函数?

8
Clojure的distinct?方法不接受集合,而是一系列参数的列表。
(distinct? x)
(distinct? x y)
(distinct? x y & more)

所以(distinct? 0 0 0 0)正确地返回false,而(distinct? [0 0 0 0])返回true。我该如何在集合上使用distinct?,以便传递一个包含重复项的集合[0 0 0 0]会返回false?

我确实意识到函数的执行是正确的,但我正在寻找一种技巧,将其应用于集合的内容而不是参数列表。

作为解决方法,我目前有:

(defn coll-distinct? [coll]
   (= (distinct coll) coll))

但我觉得我错过了一种更优雅的复用“distinct”的方式。


lol,一种将其“应用”于内容的技巧 - gtrak
1个回答

17

如果你想将参数作为序列传递给函数,请使用apply

(apply distinct? [1 2 3 1])
; false
(apply distinct? [1 2 3])
; true

如果集合为空,这种情况下会怎样工作? - Ken Liu
@KenLiu,没有0元的distinct?形式,因此(apply distinct? [])会抛出“Wrong number of args (0)” ArityException异常,与(distinct?)相同。与之相比,+确实有一个0元形式:(+)(apply + [])都返回0 - chbrown

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接