Filtering a list in dependence of that list in clojure

Viewed 59

Suppose you have the following code to get all primes until a parameter:

(defn my-filt [x z]
   (or (not= 0 (mod z x))
       (= z x)))

(defn my-filter [y x]
  (filter (partial my-filt x) y))


(defn primes [end_prime]
  (reduce my-filter
    (cons (range 2 end_prime) (range 2 end_prime))))

(primes 19)

As you can see I use partial my-filt x, because i need the list x in the my-filt function, because a filter just depends on one parameter. My question is following: Is there a better way of using idiomatic clojure not to use partial in a filter?

1 Answers

I always prefer being explicit about what you are doing, rather than using partial. For example, I would have written:

(filter  #(my-filt x %)  y)

or sometimes the full function specification:

(fn [z] (my-filt x z))

So it is clear we are calling my-filt with a fixed parameter x. The fn syntax also gives you the option to provide a descriptive name for each argument, which is often quite helpful documentation for the reader.

Of course, partial cannot be used if you have any free arg preceeding a fixed arg.

Related