hariszaman
hariszaman

Reputation: 8424

And predicate filtering clojure

I have function that takes any amount of predicates and filters the seq for each one of them like this:

 (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)
        )
)

This works as expected for 1 2 or more params like this:

(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

The problem is when I pass no parameters, it should return the original sequence how to do that?

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

Upvotes: 0

Views: 389

Answers (1)

Jordan Biserkov
Jordan Biserkov

Reputation: 691

as per the docs filter

returns a lazy sequence of the items in coll for which (pred item) returns true.

To get the original sequence, (pred item) must return true for every item.

(fn [x] true) should do the trick.

Upvotes: 1

Related Questions