wro*_*ame 2 clojure clojure-1.3
基本上,我想要一个像这样工作的函数:
user=> (pos 'c '(a b c d e f g) =)
2
user=> (pos 'z '(a b c d e f g) =)
nil
Run Code Online (Sandbox Code Playgroud)
我想出了这个:
(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)))))
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,是否有一些内置函数可以让我们这样做,或者是否有更好的,更实用的/ Clojure-ish方式来编写pos
函数?
好吧,如果你真的想要寻找一个特定的项目,你可以.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
Run Code Online (Sandbox Code Playgroud)
另一方面,有一个原因不包含在clojure.core中:它不是非常有效,而且你很少关心集合中的索引 - 如果你这样做,你通常应该重新考虑你的算法.