2013-11-04 46 views

回答

1

如果你想檢索匹配的位置的各項指標與元素一起,你可以試試這個:

(filter #(re-find #"ef" (second %)) (map-indexed vector '("abc" "def" "gih"))) 
=>([1 "def"]) 

map-indexed vector生成使用正則表達式針對的索引/值懶惰序列

user> (map-indexed vector '("abc" "def" "gih")) 
    ([0 "abc"] [1 "def"] [2 "gih"]) 

然後可以filter每個列表成員的元素。

#(re-find #"ef" (second %)) 
2

結合filterre-find可以很好地做到這一點。

user> (def fx '("abc" "def" "gih")) 
#'user/fx 

user> (filter (partial re-find #"ef") fx) 
("def") 

user> (filter (partial re-find #"a") fx) 
("abc") 

在這種情況下,我想雖然定義一個匿名函數,在這種情況下正常工作,以及將它們與partial結合起來。這也是有用的使用re-pattern,如果你不提前知道搜索字符串:

user> (filter (partial re-find (re-pattern "a")) fx) 
("abc") 
0

這是一個傳統的遞歸定義,它返回索引。很容易修改以返回相應的字符串。

(defn strs-index [re lis] 
    (let [f (fn [ls n] 
      (cond 
       (empty? ls) nil 
       (re-find re (first ls)) n 
       :else (recur (rest ls) (inc n))))] 
    (f lis 0))) 

user=> (strs-index #"de" ["abc" "def" "gih"]) 
1 
user=> (strs-index #"ih" ["abc" "def" "gih"]) 
2 
user=> (strs-index #"xy" ["abc" "def" "gih"]) 
nil 

(描述:該輔助函數f被定義爲在let結合,然後被稱爲在結束如果傳遞給它串序列不爲空時,它搜索在正則表達式如果找到了字符串,則返回索引,這就使用了re-find的結果爲真的事實,除非失敗,否則返回nil如果前面的步驟沒有成功,函數就會啓動如果它到達序列的末尾,則返回nil)

+0

優秀的迭代示例。在[lisp]中學習函數式編程的更多示例可以在[sicp](http://mitpress.mit.edu/sicp/)處找到。 –

+0

爲什麼你要在循環中綁定f? –

+0

(哇,爲什麼我得到一個downvote?)@Igrapenthin,'f'不必在'loop'中定義,當然。通常我將這種輔助函數定義爲一個單獨的命名函數,例如,稱爲「strs-index-aux」。我認爲這是完全合法的,並且可能更易於閱讀。因爲這個函數的目的只是爲了strs-index的工作,所以一個選項是用本地綁定來定義函數,這樣它就不會出現在命名空間中。不過,也許這不是你所問的。不確定。 – Mars

1

Just indices:

  • 懶洋洋地:

    (keep-indexed #(if (re-find #"ef" %2) 
            %1) '("abc" "def" "gih")) 
    => (1) 
    
  • 使用循環/復發

    (loop [[str & strs] '("abc" "def" "gih") 
         idx 0 
         acc []] 
        (if str 
        (recur strs 
          (inc idx) 
          (cond-> acc 
          (re-find #"ef" str) (conj idx))) 
        acc)) 
    

    對於剛剛元素,是指亞瑟Ulfeldts答案。

相關問題