Clojure: find repetition

Posted by demi on Stack Overflow See other posts from Stack Overflow or by demi
Published on 2013-11-10T19:40:57Z Indexed on 2013/11/11 3:53 UTC
Read the original article Hit count: 103

Filed under:

Let we have a list of integers: 1, 2, 5, 13, 6, 5, 7 and I want to find the first number has a duplicate before it and return a vector of two indices, In my sample, it's 5 at [2, 5]. What I did so far is loop, but can I do it more elegant, short way?

(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))))))

No need to return number itself, because I can get it by index and, second, it may be not always there.

© Stack Overflow or respective owner

Related posts about clojure