组合相同集合的函数
我刚开始学习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-$函数已经完全成熟(请注意,通过使谓词函数而不是隐藏谓词的整个过滤,您将获得更多的可重用性)。
因此,要使其工作,您可以使用 thread-last 宏->>:
(->> array
filter-1
filter-2)
这是一种相当通用的方法,您会经常在野外代码中看到。更一般:
(->> xs
(filter pred?)
(map tf)
(remove pred?))
较新的方法是
换能器,其中的组合是通过comp. 这也是将整个转换管道实际组合成一个新功能的方法。
例如
(def my-xf
(comp
(filter pred1)
(filter pred2)))
(into [] my-xf xs)
请注意在 上使用单参数版本filter。