【问题标题】:And predicate filtering clojure和谓词过滤clojure
【发布时间】:2014-10-26 13:36:09
【问题描述】:

我有一个函数可以接受任意数量的谓词并过滤每个谓词的序列,如下所示:

 (defn andp [& fns]
      (fn [& args]
        (every? #(apply % args) fns)))

(defn pred-and
      ([] "what to return")
      ([x] x)
      ([x y] (andp x y))
      ([x y & more]
          (reduce pred-and (pred-and x y) more)
        )
)

对于像这样的 1 2 或更多参数,这可以正常工作:

(filter (pred-and pos? odd?) [1 2 -4 0 6 7 -3]) => [1 7] // For one parameter

(filter (pred-and number? integer? pos? even?)             [1 0 -2
:a 7 "a" 2])                   => [2] // For two parameters

问题是当我不传参数时,它应该返回原来的序列怎么办?

(filter (pred-and) [1 0 -2]) => [1 0 -2]

【问题讨论】:

    标签: clojure functional-programming


    【解决方案1】:

    根据docs 过滤器

    返回 coll 中 (pred item) 返回 true 的项的惰性序列。

    要得到原始序列,(pred item) 必须为每个 item 返回 true。

    (fn [x] true) 应该可以解决问题。

    【讨论】:

    • 感谢它的工作只是问我正在返回 true 并且它没有工作但是当我返回时 (fn [x] true) 它工作了为什么?
    • spec 说:> 如果没有给定参数,则返回一个始终返回 true 的谓词 谓词是函数,其值用于布尔上下文中
    • (constantly true) 会更惯用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多