如何在向量中找到项目的索引?

时间:2011-01-28 16:56:58

标签: clojure

????应该是什么想法?内置了吗? 什么是完成这项任务的最佳方法?

(def v ["one" "two" "three" "two"])

(defn find-thing [ thing vectr ]
  (????))

(find-thing "two" v) ; ? maybe 1, maybe '(1,3), actually probably a lazy-seq

9 个答案:

答案 0 :(得分:119)

内置:

user> (def v ["one" "two" "three" "two"])
#'user/v
user> (.indexOf v "two")
1
user> (.indexOf v "foo")
-1

如果你想要所有匹配的索引的延迟seq:

user> (map-indexed vector v)
([0 "one"] [1 "two"] [2 "three"] [3 "two"])
user> (filter #(= "two" (second %)) *1)
([1 "two"] [3 "two"])
user> (map first *1)
(1 3)
user> (map first 
           (filter #(= (second %) "two")
                   (map-indexed vector v)))
(1 3)

答案 1 :(得分:40)

Stuart Halloway在这篇文章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)

如果您想获取第一个值,只需在结果上使用first

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

编辑:因为clojure.contrib.seq已经消失了,我用一个简单的实现示例更新了我的答案:

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

答案 2 :(得分:24)

(defn find-thing [needle haystack]
  (keep-indexed #(when (= %2 needle) %1) haystack))

但是我想警告你不要摆弄指数:通常情况下它会产生较少惯用,笨拙的Clojure。

答案 3 :(得分:13)

从Clojure 1.4开始,clojure.contrib.seq(以及positions函数)不可用,因为它缺少维护者: http://dev.clojure.org/display/design/Where+Did+Clojure.Contrib+Go

clojure.contrib.seq/positions及其依赖关系clojure.contrib.seq/indexed的来源是:

(defn indexed
  "Returns a lazy sequence of [index, item] pairs, where items come
  from 's' and indexes count up from zero.

  (indexed '(a b c d))  =>  ([0 a] [1 b] [2 c] [3 d])"
  [s]
  (map vector (iterate inc 0) s))

(defn positions
  "Returns a lazy sequence containing the positions at which pred
   is true for items in coll."
  [pred coll]
  (for [[idx elt] (indexed coll) :when (pred elt)] idx))

(positions #{2} [1 2 3 4 1 2 3 4]) => (1 5)

此处可用:http://clojuredocs.org/clojure_contrib/clojure.contrib.seq/positions

答案 4 :(得分:5)

我试图回答我自己的问题,但布莱恩用更好的答案打败了我!

(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

答案 5 :(得分:2)

我最近不得不多次找到索引,或者我选择了索引,因为它比找出另一种解决问题的方法更容易。在此过程中,我发现我的Clojure列表没有.indexOf(Object object,int start)方法。我像这样处理问题:

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

答案 6 :(得分:2)

这是我的贡献,使用loop结构并在失败时返回nil

我尽量避免循环,但这似乎适合这个问题。

(defn index-of [xs x]
  (loop [a (first xs)
         r (rest xs)
         i 0]
    (cond
      (= a x)    i
      (empty? r) nil
      :else      (recur (first r) (rest r) (inc i)))))

答案 7 :(得分:0)

我会用reduce-kv

(defn find-index [pred vec]
  (reduce-kv
    (fn [_ k v]
      (if (pred v)
        (reduced k)))
    nil
    vec))

答案 8 :(得分:0)

如果我们需要第一个索引,我们不需要循环整个集合。 some 函数将在第一次匹配后短路。

(defn index-of [x coll]
  (let [idx? (fn [i a] (when (= x a) i))]
  (first (keep-indexed idx? coll))))