Подтвердить что ты не робот

Как найти индекс элемента в векторе?

Любые идеи, что ???? должно быть? Есть встроенный? Каким будет лучший способ выполнить эту задачу?

(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
4b9b3361

Ответ 1

Встроенные:

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

Если вам нужен ленивый сегмент индексов для всех совпадений:

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)

Ответ 2

Стюарт Халлоуэй дал действительно хороший ответ в этом сообщении http://www.mail-archive.com/[email protected]/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

EDIT: Поскольку clojure.contrib.seq исчез, я обновил свой ответ на примере простой реализации:

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

Ответ 3

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

Но я хотел бы предупредить вас о том, что вы не играете с индексами: чаще всего он будет производить меньше идиоматических, неудобных Clojure.

Ответ 4

В соответствии с 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

Ответ 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

Ответ 6

Недавно мне приходилось находить индексы несколько раз или, скорее, я выбрал, поскольку это было проще, чем выяснение другого способа приближения к проблеме. По пути я обнаружил, что в моих списках 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)))))

Ответ 7

Здесь мой вклад, используя структуру loop ing и возвращающий 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)))))