Clojure:寻找重复

dem*_*emi 2 clojure

假设我们有一个整数列表:1, 2, 5, 13, 6, 5, 7我想找到第一个重复的数字并返回两个索引的向量。在我的示例中,它是 5 at [2, 5]。到目前为止我所做的是loop,但我可以做得更优雅、更短吗?

(defn get-cycle
  [xs]
  (loop [[x & xs_rest] xs, indices {}, i 0]
    (if (nil? x)
      [0 i]  ; Sequence is over before we found a duplicate.
      (if-let [x_index (indices x)]
        [x_index i]
        (recur xs_rest (assoc indices x i) (inc i))))))
Run Code Online (Sandbox Code Playgroud)

不需要返回数字本身,因为我可以通过索引获取它,其次,它可能并不总是存在。

tra*_*ard 5

使用列表处理的选项,但不是更简洁:

(defn get-cycle [xs]
  (first (filter #(number? (first %))
    (reductions
      (fn [[m i] x] (if-let [xat (m x)] [xat i] [(assoc m x i) (inc i)]))
      [(hash-map) 0] xs))))
Run Code Online (Sandbox Code Playgroud)