How do I find the index of an item in a vector?

后端 未结 8 1915
孤独总比滥情好
孤独总比滥情好 2020-11-29 01:13

Any ideas what ???? should be? Is there a built in? What would be the best way to accomplish this task?

(def v [\"one\" \"two\" \"three\" \"two         


        
8条回答
  •  一个人的身影
    2020-11-29 01:24

    Stuart Halloway has given a really nice answer in this post http://www.mail-archive.com/clojure@googlegroups.com/msg34159.html.

    (use '[clojure.contrib.seq :only (positions)])
    (def v ["one" "two" "three" "two"])
    (positions #{"two"} v) ; -> (1 3)
    

    If you wish to grab the first value just use first on the result.

    (first (positions #{"two"} v)) ; -> 1
    

    EDIT: Because clojure.contrib.seq has vanished I updated my answer with an example of a simple implementation:

    (defn positions
      [pred coll]
      (keep-indexed (fn [idx x]
                      (when (pred x)
                        idx))
                    coll))
    

提交回复
热议问题