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

后端 未结 8 1876
孤独总比滥情好
孤独总比滥情好 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:31

    I was attempting to answer my own question, but Brian beat me to it with a better answer!

    (defn indices-of [f coll]
      (keep-indexed #(if (f %2) %1 nil) coll))
    
    (defn first-index-of [f coll]
      (first (indices-of f coll)))
    
    (defn find-thing [value coll]
      (first-index-of #(= % value) coll))
    
    (find-thing "two" ["one" "two" "three" "two"]) ; 1
    (find-thing "two" '("one" "two" "three")) ; 1
    
    ;; these answers are a bit silly
    (find-thing "two" #{"one" "two" "three"}) ; 1
    (find-thing "two" {"one" "two" "two" "three"}) ; nil
    
    0 讨论(0)
  • 2020-11-29 01:35

    I recently had to find indexes several times or rather I chose to since it was easier than figuring out another way of approaching the problem. Along the way I discovered that my Clojure lists didn't have the .indexOf(Object object, int start) method. I dealt with the problem like so:

    (defn index-of
    "Returns the index of item. If start is given indexes prior to
     start are skipped."
    ([coll item] (.indexOf coll item))
    ([coll item start]
      (let [unadjusted-index (.indexOf (drop start coll) item)]
        (if (= -1 unadjusted-index)
      unadjusted-index
      (+ unadjusted-index start)))))
    
    0 讨论(0)
提交回复
热议问题