![](/img/trans.png)
[英]How do I run multiple functions which operate on the same collection, but only traverse the collection once? (clojure, example included)
[英]Combine functions for same collection
我剛開始學習Clojure
,然后我用其他功能語言創建了一些具有以下功能的管道
val result = filter(something)
map(something)
reduce(something)
collection
我正在嘗試使用 Clojure 結合兩個filter
功能來實現類似的功能
(defn filter-1 [array] (filter
(fn [word] (or (= word "politrons") (= word "hello"))) array))
(defn filter-2 [array] (filter
(fn [word] (= word "politrons")) array))
(def result (filter-1 ["hello" "politrons" "welcome" "to" "functional" "lisp" ""]))
(println "First:" result)
(println "Pipeline:" ((filter-2 result)))
但我無法讓它工作。
您能否提供一些關於如何將兩個predicate
函數組合到同一個collection
的建議或文檔?
問候
您的兩個filter-$
函數已經完全成熟(注意,通過使您的謂詞函數而不是隱藏謂詞的整個過濾,您將獲得更多的可重用性)。
因此,要使其工作,您可以 go 使用 thread-last 宏->>
:
(->> array
filter-1
filter-2)
這是一種相當通用的方法,你會經常在野外的代碼中看到。 更一般的:
(->> xs
(filter pred?)
(map tf)
(remove pred?))
較新的方法是傳感器,其中組合是通過comp
完成的。 這也是將整個轉換管道實際組合到新的 function 的方法。
例如
(def my-xf
(comp
(filter pred1)
(filter pred2)))
(into [] my-xf xs)
請注意在filter
上使用單參數版本。
有一些選項可以組成處理步驟:
你可以像這樣管道過濾器調用:
(->> data
(filter #{"politrons" "hello"})
(filter #{"politrons"}))
;;=> ("politrons")
注意這些詞集被用作過濾函數(只是你的那些相等謂詞的快捷方式)
但我想你需要知道的是傳感器的概念,因為它的用途包括(但不限於)你需要的這種類型的流水線:
(eduction (filter #{"politrons" "hello"})
(filter #{"hello"})
data)
;;=> ("hello")
如果您只需要過濾,您還可以將過濾器 function 與更高級別的功能(如every-pred
)結合使用:
(filter (every-pred #{"politrons" "hello"}
#(= "olleh" (clojure.string/reverse %)))
data)
;;=> ("hello")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.