Алгоритмы / Поиск

;; the plain scan: walk the vector until the item is met
(defn search [v x]
  (loop [i 0]
    (cond
      (= i (count v)) nil
      (= (v i) x) i
      :else (recur (inc i)))))

(def items [2 3 5 7 11 13 17])

(println (search items 1))   ; nil
(println (search items 7))   ; 3
(println (search items 19))  ; nil

;; *** simplified speed test ***
(def big (vec (range 100000)))
(time (search big 77777))
;; about 8 msecs

;; the same scan written the Clojure way
(println (first (keep-indexed #(when (= %2 7) %1) items)))