Clojure position subsequence in sequence

Does Clojure provide any built-in way to find the position of a subsequence in a given sequence?

+5
source share
2 answers

Clojure provides a built-in way for easy Java Interop .

(java.util.Collections/indexOfSubList '(a b c 5 6 :foo g h) '(5 6 :foo))
;=> 3
+7
source

A sequence is an abstraction, not a nodule. Some nodules that you can use through abstraction of a sequence have a way to find the position of a subsequence (for example, strings and java collections), but sequences generally do not do this, since the base nodule should not have an index.

. map-indexed.

, () () . 1, :

(defn find-pos
  [sq sub]
  (->>
    (partition (count sub) 1 sq)
    (map-indexed vector)
    (filter #(= (second %) sub))
    (map first)))

=> (find-pos  [:a :b \c 5 6 :foo \g :h]
                [\c 5 6 :foo])
(2)

=> (find-pos  "the quick brown fox"
                (seq "quick"))
(4)

, -, . , , .

+3

All Articles