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
1.2k views
in Technique[技术] by (71.8m points)

clojure - Simplify a filter clause with many predicates that depend on context

I am new to Clojure and am still trying to wrap my head around doing things the "Clojure way". One function that I'm currently writing requires me to filter a collection (pile) with several predicates, but the set of predicates to use depends on several function arguments (in this case ref-base and single-ended?). Here is the code I currently have:

(filter (every-pred
        qcpass?
        (case ref-base
          "C" (if single-ended?
               #(not (reverse? %))
               #(and (properly-paired? %) (or (f1? %) (r2? %))))
          "G" (if single-ended?
               reverse?
               #(and (properly-paired? %) (or (f2? %) (r1? %))))
          nil?) ;; skip all piles if we're in a non-C/G position
        ) pile))

I feel that there is probably a better/more concise way to write this, since there is still some repetition of code in there, and a lot of parentheses. I'm also unhappy, aestetically, with the inline functions (#(..)) to use and/or/not within a filter. Could I ask for suggestions how to make this whole expression "prettier"?

question from:https://stackoverflow.com/questions/65917627/simplify-a-filter-clause-with-many-predicates-that-depend-on-context

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

1 Reply

0 votes
by (71.8m points)

Not sure this will be much "prettier" (that is a matter of taste) but here is a suggestion to take apart the logic of (case ref-base ...) and (if single-ended? so they are not nested:

(filter (every-pred qcpass?
                    (let [pred (fn [r f0? f1?]
                                 (if single-ended?
                                   #(= r (reverse? %))
                                   #(and (properly-paired? %)
                                         (or (f0? %) (f1? %)))))]
                      (case ref-base
                        "C" (pred false f1? r2?)
                        "G" (pred true f2? r1?)
                        nil?)))
        pile)

I have not tested this code and I don't know if it has bugs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

57.0k users

...