Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

Filtering a list in dependence of that list in clojure

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?

question from:https://stackoverflow.com/questions/65894222/filtering-a-list-in-dependence-of-that-list-in-clojure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...