2

本质上,我想要一个像这样工作的函数:

user=> (pos 'c '(a b c d e f g) =)
2
user=> (pos 'z '(a b c d e f g) =)
nil

我想出了这个:

(defn pos
  "Gets position of first object in a sequence that satisfies match"
  [object sequence match]
  (loop [aseq sequence position 0]
    (cond (match object (first aseq)) position
          (empty? aseq) nil
          :else (recur (rest aseq) (inc position)))))

所以我的问题是,是否有一些内置函数可以让我们这样做,或者是否有更好、更实用/Clojure-ish 的方式来编写pos函数?

4

1 回答 1

5

好吧,如果您真的想寻找可以.indexOf在收藏中使用的特定物品;如果你想用谓词做一些更一般的事情,你不需要一个函数一个项目,一个函数就足够了。

(defn pos [pred coll]
  (->> coll
       (map-indexed #(when (pred %2) %1))
       (remove nil?)
       (first)))

user> (pos #{'c} '(a b c d e f g))
2

另一方面,clojure.core 中没有包含它是有原因的:它效率不高,而且您很少关心集合中的索引 - 如果您这样做,您通常应该重新考虑您的算法。

于 2012-01-01T05:27:11.120 回答