【问题标题】:Finding the position of an object in a sequence in Clojure在 Clojure 中查找序列中对象的位置
【发布时间】:2012-01-01 04:11:44
【问题描述】:

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

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 函数?

【问题讨论】:

标签: clojure clojure-1.3


【解决方案1】:

好吧,如果你真的想寻找某个特定的项目,你可以在集合上使用.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 中没有包含它是有原因的:它效率不高,而且您很少关心集合中的索引 - 如果您这样做,您通常应该重新考虑您的算法。

【讨论】:

    猜你喜欢
    • 2020-01-25
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2021-12-21
    • 2012-04-06
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    相关资源
    最近更新 更多