[英]Combine functions for same collection
I just start learning Clojure
, and I get used in other functional language create some pipelines with functions like我刚开始学习
Clojure
,然后我用其他功能语言创建了一些具有以下功能的管道
val result = filter(something)
map(something)
reduce(something)
collection
I'm trying to achieve something like that with Clojure combining two filter
functions我正在尝试使用 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)))
But I'm unable to make it works.但我无法让它工作。
Could you please can provide some advice or documentation of how to combine two predicate
functions for a same collection
?您能否提供一些关于如何将两个
predicate
函数组合到同一个collection
的建议或文档?
Regards问候
Your two filter-$
functions are fully fledged already (Note, that you would gain more re-usability by making your predicates functions and not the whole filtering with the predicate hidden).您的两个
filter-$
函数已经完全成熟(注意,通过使您的谓词函数而不是隐藏谓词的整个过滤,您将获得更多的可重用性)。
So to make that work, you can go with the thread-last macro ->>
:因此,要使其工作,您可以 go 使用 thread-last 宏
->>
:
(->> array
filter-1
filter-2)
This is a rather general approach, you will see often in code in the wild.这是一种相当通用的方法,你会经常在野外的代码中看到。 More general:
更一般的:
(->> xs
(filter pred?)
(map tf)
(remove pred?))
The newer approach for this are transducers , where the combination is done via comp
.较新的方法是传感器,其中组合是通过
comp
完成的。 And this would also be the way to actually combine your whole transformation pipeline into a new function.这也是将整个转换管道实际组合到新的 function 的方法。
Eg例如
(def my-xf
(comp
(filter pred1)
(filter pred2)))
(into [] my-xf xs)
Note the use of the single argument version on filter
.请注意在
filter
上使用单参数版本。
there are some options to compose processing steps:有一些选项可以组成处理步骤:
you can just pipeline filter calls like this:你可以像这样管道过滤器调用:
(->> data
(filter #{"politrons" "hello"})
(filter #{"politrons"}))
;;=> ("politrons")
notice these word sets to be used as filter functions (just a shortcut for those equality predicates of yours)注意这些词集被用作过滤函数(只是你的那些相等谓词的快捷方式)
but i guess what you need to know, is the transducers concept, since it's usages include (but not limited to) this type of pipelining you need:但我想你需要知道的是传感器的概念,因为它的用途包括(但不限于)你需要的这种类型的流水线:
(eduction (filter #{"politrons" "hello"})
(filter #{"hello"})
data)
;;=> ("hello")
in case you just need filtering, you can also combine filter function with higher-level functions like every-pred
:如果您只需要过滤,您还可以将过滤器 function 与更高级别的功能(如
every-pred
)结合使用:
(filter (every-pred #{"politrons" "hello"}
#(= "olleh" (clojure.string/reverse %)))
data)
;;=> ("hello")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.