繁体   English   中英

为同一集合组合功能

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM