2012-01-01 46 views
2

從本質上講,我想這是這樣的一個功能:找到一個對象的位置對序列中的Clojure

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方法來編寫pos函數?

+1

你可以使用'keep-indexed' - 看到這個問題: http://stackoverflow.com/questions/8641305/how-do-i-find-the-index-of-an-element-that- match-a-predicate-in-clojure – Gert 2012-01-01 05:49:22

+0

和另一個與相同的問題:http://stackoverflow.com/questions/4830900/how-do-i-find-the-index-of-an-item-in- a-vector – Gert 2012-01-01 05:51:20

+0

@gertalot謝謝!這些鏈接對我也有幫助 – wrongusername 2012-01-01 22:40:15

回答

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一個原因:它不是很有效,你很少在乎集合中的指數 - 如果你這樣做,你通常應該重新考慮你的算法。

相關問題