当可能存在重复时,我想在两个 [列表、向量、序列] 中找到共同的元素。
(common-elements [1] [1]) ; [1]
(common-elements [1 2] [1 1]) ; [1]
(common-elements [1 1] [1 1 1]) ; [1 1]
这是我目前拥有的:
(defn remove-first [elem coll]
(lazy-seq
(when-let [s (seq coll)]
(let [f (first s), r (rest s)]
(if (= elem f)
r
(cons f (remove-first elem r)))))))
(defn common-elements [coll1 coll2]
(lazy-seq
(when (and (seq coll1) (seq coll2))
(let [f (first coll1)]
(if (some #{f} coll2)
(cons f (common-elements (rest coll1)
(remove-first f coll2)))
(common-elements (rest coll1) coll2)))))
我使用4clojure的经验告诉我,我很少编写最惯用或最简洁的代码,所以我很想知道是否有更好的方法来做到这一点。